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!