C++模板分为函数模板和类模板。
函数模板
#include <iostream>
using namespace std;
/*
函数模板:
template <class(也可以用typename) T>
返回类型 函数名( 形参表 )
{
//函数定义体
}
类模板:
template <class(也可以用typename) T>
class 类名
{
//类定义
}
*/
template <typename type1,typename type2>
void template_test(type1 param1,type2 param2)
{
cout << "param1: ";
cout << param1;
cout << endl;
cout << "param2: ";
cout << param2;
cout << endl;
cout << "--------------------" << endl;
}
int main(char *argv,int argc)
{
template_test(10,20);
template_test("hello","world");
template_test(30,"Hello world");
cout<< endl << "Test over!" << endl;
return 0;
}
运行以上代码,结果如下:
param1: 10
param2: 20
--------------------
param1: hello
param2: world
--------------------
param1: 30
param2: Hello world
--------------------
Test over!
#include <iostream>
using namespace std;
/*
函数模板:
template <class(也可以用typename) T>
返回类型 函数名( 形参表 )
{
//函数定义体
}
类模板:
template <class(也可以用typename) T>
class 类名
{
//类定义
}
*/
template <typename type1,typename type2>
class TemplateTest
{
public:
TemplateTest(type1 a,type2 b){
param1 = a;
param2 = b;
}
~TemplateTest(){}
public:
void printParams(){
cout << "param1: ";
cout << param1;
cout << endl;
cout << "param2: ";
cout << param2;
cout << endl;
cout << "--------------------" << endl;
}
private:
type1 param1;
type2 param2;
};
int main(char *argv,int argc)
{
//定义类对象的时候,要指定参数类型
TemplateTest<int,char*> templateTest(10,"hello world");
templateTest.printParams();
cout<< endl << "Test over!" << endl;
return 0;
}
运行上述代码,结果如下:
param1: 10
param2: hello world
--------------------
Test over!
非类型模版参数(常量参数)
#include <iostream>
using namespace std;
/*
非类型模版参数(常量参数)
定义一个确定类型的常量作为模板参数,
这个常量不作为函数参数,
因此在实际调用函数时,
传递的函数参数中不包括这个参数。
*/
template <int SIZE,typename type>
void template_test(type param)
{
char array[SIZE];
cout << "Array size is " << sizeof(array) << endl;
cout << "SIZE = " << SIZE << endl;
cout << "param = " << param << endl;
cout << "--------------------" << endl;
}
int main(char *argv,int argc)
{
//传递的函数参数中不包括SIZE这个参数
template_test<55>("hello world");
cout<< endl << "Test over!" << endl;
return 0;
}
执行上述代码,得到的结果如下:
Array size is 55
SIZE = 55
param = hello world
--------------------
Test over!