1.函數模闆
template<typename T1,typename T2>
void fun(T1 a, T2 b)//定義了a,b兩個數
{
cout << "這是一個函數模闆" << endl;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
template<>
void fun(int a,string b)//fun函數的特例化
{
cout << "這是一個函數模闆的特例化" << endl;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
int main()
{
string s = "張三";
fun(2, 2);//調用了函數模闆
fun(1,s);//調用了函數特例化模闆
}
2.類模闆的特例化
template<typename T1, typename T2>
class student
{
public:
student()
{
cout << "這是一個類模闆" << endl;
}
T1 a;
T2 b;
};
template<typename T2>
class student<int, T2>
{
public:
student(int a, T2 b) :a(a), b(b)
{
cout << "這是一個類模闆偏特化" << endl;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
int a = 10;
T2 b;
};
template<>
class student<int, string>
{
public:
student(int c, string d):a(c),b(d)
{
cout << "這是一個類模闆全特化" << endl;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
int a;
string b;
};
int main()
{
student<char,int>s;
student<int,double> s2(1,2.56);
student<int, string>s3(1, "李四");
return 0;
}