模板函数

1 解决,不同类型数据的相同操作写大量冗余的代码

2 函数模板不是一个实在的函数,编译器不能为其生成可执行代码。定义函数模板后只是一个对函数功能框架的描述,当它具体执行时,将根据传递的实际参数决定其功能(百度百科)

3示例

// demo1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

template<typename T>
void Swap(T &a,T &b)
{
   T x = a;
   a = b;
   b = x;
   return;
}
template<typename T>//每个函数都要重新写一次在函数头
T Sum(T *X,T *Y)
{
    printf("SUM !");
    *X = *X + 2.0;
    return (*Y + *X);

}

template<class A,class B>
void printstr(A a,B b)
{
    std::cout<<a<<"-----"<<b<<std::endl;
}

int sum2(int a ,int b)
{
    printf(" sum2!");
    return (a*2 + b);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int x =1,y=2;
    Swap(x,y);

    float x1=0.0,x2 =1.1;
    Swap(x1,x2);

    printf("%d, %d, %f ,%f",x,y,x1,x2);
//-----------------------------------------------------
    getchar();

    float a =3.222;
    float b = 2.123;
    printf("%f, %f, %d",a,Sum(&a,&b),sum2(3,5));//从右到左先逐个计算各个表达式,然后从左到右逐个输出。
    getchar();
//-----------------------------------------------------
    char* str = "cccccccccc";
    int m = 0;
    printstr(str,m);
    getchar();

    return 0;
}

4 类模板

什么是默认构造函数:

A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter). A type with a public default constructor is DefaultConstructible.

//在.H中声明,注意你要用这个函数,就一定要定义所有会用到的东西,不能光声明
//仅声明不定义,会出现函数无法解析

#include <iostream>
template<typename T>
class TestC{
public:

    TestC();//这个是默认构造,不写,编译器给你生成;不过一旦显示的写出来了,就要你自己定义
    ~TestC();
    void setT(T t1);
    void PrintT();
private:
    T t;
};
//.cpp
#include "stdafx.h"
#include <iostream>
#include "Testc.h"

template<typename T>
TestC<T>::TestC(){};
template<typename T>
TestC<T>::~TestC(){};

template<typename T>
void TestC<T>::setT(T t1)
{
    this->t = t1;
}

template<typename T>
void TestC<T>::PrintT()
{
    std::cout<<this->t <<std::endl;;
}


int _tmain(int argc, _TCHAR* argv[])
{
    
    TestC<char*> A;
    A.setT("test t");
    A.PrintT();
    getchar();

    return 0;
}
//构造函数如果不写,编译器生成默认无参构造。显示的写了构造,就必须实现它;
原文地址:https://www.cnblogs.com/8335IT/p/15003869.html