模板顯示具體化

什麼是顯示具體化

模板能夠針對某種具體的類型使用不同的算法(函數體或類體不同)
例如

template<class T> const T& Max(const T& a, const T& b){
    return a > b ? a : b;
}

大於符號 > 等運算符並不能用於機構體,類的比較(需要重載),對於上的問題當T爲結構體或者是類時,需要顯示具體化

顯示具體化實現

注意:必須要先有了函數模板,才能對函數模板實現顯示具體化
具體步驟

  1. 聲明函數模板
  2. 對已聲明的函數模板具體化,不能改變函數名,函數返回值,函數參數。
    2.1 函數模板具體化時,模板頭寫成template<>,函數名後面<參數類型>
    例如:template<>void compare(const stu &s1, const stu & s2);stu是定義的一個類
    2.2 也可以省略寫作
    template<>void compare(const stu &s1, const stu & s2);
    因爲編譯器可以根據參數類型推斷出來其具體類型。
    2.3 如果沒有完全具體化
    template < class T2 > void compare(const stu &s1, T2 & s2);stu是定義的
#include <iostream>
#include<string>
using namespace std;
class stu{
public:
	stu(string name, int score) :m_name(name), m_score(score){}
	string m_name;
	int m_score;
};
ostream& operator<<(ostream &os, const stu&s){
	os << " name = " << s.m_name << " score = " << s.m_score << endl;
	return os;
}
template<class T> //聲明函數模板,這一步一定要有即使不定義都沒問題,
但是具體化的函數必須要和模板函數一模一樣(即返回值,函數名,參數類型)。
void compare(const T& a, const T& b);
template<>//具體化 應爲聲明瞭具體類型<>中不用在class T
void compare<stu>(const stu &s1, const stu & s2);
int main()
{
	stu s1("zhang3", 92);
	stu s2("li4", 95.3);
	compare(s1, s2);
	system("pause");
	return 0;
}

template<>
void compare<stu>(const stu &s1, const stu & s2){
	operator<<(cout, s1.m_score > s2.m_score ? s1 : s2);
}

函數優先級

非模板函數>顯示具體化函數>常規模板函數

  • 先看 顯示具體化函數>常規模板函數
template<class T>
void func(T t){
	cout << " model func " << endl;
}
template<>
void func<char>(char t){
	cout << " special model func" << endl;
}
int main()
{
	func(1);//model func
	func('f');//spicial mode func
	system("pause");
	return 0;
}

再加入普通函數

void func(int n = 0){
	cout << " normal func" << endl;
}
template<class T>
void func(T t){
	cout << " model func " << endl;
}
template<>
void func<char>(char t){
	cout << " special model func" << endl;
}
int main()
{
	func();//normal func
	func(1);//normal func
	func('f');//spicial mode func
	func(1.111);//model func
	system("pause");
	return 0;
}

類的具體化和函數模板的具體化一樣,只是類的成員函數不用再加模板頭

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章