模板(Template)
简单的说,模板是一种通用的描述机制,当使用模板时允许使用通用类型来定义函数或类等。模板引入了一种全新的编程思维方式,称为"泛型编程"或"通用编程"。
类型参数化
先看下面的示例代码:
#include<iostream>
#include<string>
using namespace std;
int add(const int a, const int b)
{
cout<<"func 1"<<endl;
return a + b;
}
double add(const double a, const double b)
{
cout<<"func 2"<<endl;
return a + b;
}
char* add(char* a, const char* b)
{
cout<<"func 3"<<endl;
return strcat(a, b);
}
int main()
{
cout<<add(1, 2)<<endl;
cout<<add(1.0, 2.02)<<endl;
char x[20] = "Hello";
char y[] = " c++";
cout<<add(x, y)<<endl;
return 0;
}
运行结果如下:
func 1
3
func 2
3.02
func 3
Hello c++
上面代码分别重载了三个add函数,编译器根据传递的参数决定调用的函数。
下面是使用了函数模板的示例:
#include<iostream>
#include<string>
using namespace std;
template<class T>
T add(const T& a, const T& b)
{
return a + b;
}
int main()
{
cout<<add(1, 2)<<endl;
cout<<add(1.0, 2.02)<<endl;
string x = "Hello";
string y = " c++";
cout<<add(x, y)<<endl;
return 0;
}
运行结果如下:
3
3.02
Hello c++
模板的定义
template<class T>
或者
template<typename T>
函数模板
template<模板参数表>
返回类型 函数名(参数表)
{
//函数体
}
显示实例化
template 返回类型 函数名<类型实参表>(函数参数表);
特化
template<>返回类型 函数名[<类型实参表>](函数参数表)
{
//函数体
}