一、简介
正常的C++编程无法应对参数类型变化的问题,于是引入了模板,通过模板将类型作为一个参数进行传递,通常可以通过类型的推演自动传递,如Max(1,2)可以推导出两个类型都为int,并将这个类型传递给函数,也可以通过直接定义进行传递,如Max<int>(1,2),这种就是明确的将类型作为参数传递。函数模板的执行时会根据传递的类型生成一些新的函数,称为模板函数,而这部分内容是编译器在后台完成的。函数模板的的定义方式如下:
template<typename Type>
Type Max(Type x, Type y){......}
当然也可以定义多种类型,如:
template<typename Type1, typename Type2>
Type1 Max(Type1 x, Type2 y){......}
二、实例
比如对于一个求Max的函数,可能该函数有多种类型的实参,如果用普通的C++来编写需要定义很多个重载函数,所以采用函数模板来进行定义,具体如下:
#include <iostream>
class Test;
std::ostream& operator<<(std::ostream& out, const Test& t);
class Test{
public:
friend std::ostream& operator<<(std::ostream& out, const Test& t);
public:
bool operator>(const Test& t){
return true;
}
};
std::ostream& operator<<(std::ostream& out, const Test& t){
out<<"class Test";
return out;
}
template<typename Type>
Type Max(Type x, Type y){
return x>y?x:y;
}
#include <iostream>
#include "template.h"
int main(int argc, char** argv){
Test t1, t2;
std::cout<<Max(1,12)<<std::endl;
std::cout<<Max(1.0f,12.0f)<<std::endl;
std::cout<<Max(3.0,5.0)<<std::endl;
std::cout<<Max('A','D')<<std::endl;
std::cout<<Max(t1,t2)<<std::endl;
}
三、与普通函数差别
对于普通函数对有些情况会自动对实参进行强制类型转换,如Max(1, 1.2),但是模板类不会,因为通过类型推演会得出一个类型是int,一个类型是double,所以会存在矛盾导致函数模板不能生成正确的模板函数,进而无法正确调用。有以下几种解决方法:
(1)强制类型转换
Max(1, (int)1.2)
Max((double)1, 1.2)
(2)明确传递的类型
Max<int>(1, 1.2)
Max<double>(1, 1.2)
(3)定义多种类型的函数模板
template<typename Type1, typename Type2>
Type1 Max(Type1 x, Type2 y){return x>y?x:y;}