以 template 方式建構 function 或 class 時,可以在執行時或宣告時才定義 data type。
1. template function
範例1
#include <iostream>
using namespace std;
template<class T>
T MaxTest(T x, T y)
{
if(x > y)
return x;
return y;
}
int main()
{
cout<<"MaxTest(3, 4)="<<MaxTest(3, 4)<<endl;
cout<<"MaxTest(6.3, 8.7)="<<MaxTest(6.3, 8.7)<<endl;
cout<<"MaxTest('O', 'A')="<<MaxTest('O', 'A')<<endl;
system("pause");
return 0;
}
執行結果

範例2
#include <iostream>
using namespace std;
template<class TypeA>
TypeA TestMax(TypeA *pData, int nSize)
{
TypeA maxValue;
maxValue = pData[0];
for(int i = 0 ; i < nSize ; ++i)
{
if(maxValue < pData[i])
maxValue = pData[i];
}
return maxValue;
}
int main()
{
char a[4] = {'A', 'B', 'C', 'D'};
int b[5] = {1, 5, 9, 86, 17};
float c[3] = {9.82f, 86.47f, 42.3f};
cout<<TestMax(a, 4)<<endl;
cout<<TestMax(b, 5)<<endl;
cout<<TestMax(c, 3)<<endl;
system("pause");
return 0;
}
執行結果

範例3
#include <iostream>
using namespace std;
template<class TypeA, class TypeB>
int MaxTest(TypeA x, TypeB y)
{
if(x > y) return (int)x;
return (int)y;
}
int main()
{
cout<<MaxTest(3, 4)<<endl;
cout<<MaxTest('A', 5)<<endl;
cout<<MaxTest(3.4f, 2L)<<endl;
system("pause");
return 0;
}
執行結果

2. template class
範例
#include <iostream>
using namespace std;
template<class T>
class CObj
{
private:
T m_data;
public:
CObj(T x);
void Showdata();
};
template<class T>
CObj<T>::CObj(T x)
{
m_data = x;
}
template<class T>
void CObj<T>::Showdata()
{
cout<<"data = "<<m_data<<endl;
}
int main()
{
CObj<int> X(10);
CObj<char> Y('A');
X.Showdata();
Y.Showdata();
system("pause");
return 0;
}
執行結果

延伸閱讀
C++ -Template 的連結問題
https://husking-studio.com/cpp-template-02-unresolved-externals/