template
template用於重載(overriding),目的是讓形參類型不同的函數可以共用一個類名或者函數名。
- 最簡單的使用,對一個函數進行重載,參數是可變的
原型:
template <class identifier> function_declaration;
NOTICE:
T也可以作爲函數的返回值進行設置,並不一定是參數。
例子:
#include <iostream>
using namespace std;
template <typename T>
void show(T t)
{
cout << "the parm is " << t << endl;
}
int main()
{
show(123);
show("abc");
return 1;
}
- 和類一起使用,對參數進行限制
原型:
template <typename identifier> function_declaration;
例子
#include <iostream>
using namespace std;
template <class T> class TemC
{
public:
//並不是每一個函數都需要設置動態類型
void show(T t);
};
template <typename T> void TemC<T>::show(T t)
{
cout << "the parm is " << t << endl;
}
int main()
{
//設置T爲int之後,函數就只能接受int類型的參數
TemC<int> tempC;
tempC.show(123);
//tempC.show("abc");
return 1;
}