模板的特化,偏特化,實例化

/************************************************************************/  
/*  
文件名: 模板的特化,偏特化,實例化 
創建人: Clark/陳澤丹 
描述:   
模板特化其實就是模板的特殊處理(調用時需指定類型,然後再特殊問題特殊處理)。 
模板偏特化其實就是模板的部份特殊處理(調用時需指定類型,然後再特殊問題特殊處理)。 
模板的實例化(調用時無需指定類型了) 
創建日期: 20111006 
*/  
/************************************************************************/  
#include <iostream>   


using namespace std;  


#define TEMP_TRUE true   


#ifdef TEMP_TRUE   
//必須有定義過is_template,後面關於is_template的特化,偏特化和實例化纔可實現   
//普通模板   
template <class T1, class T2>  
struct is_template{ enum { value = 0}; };   
//也可只聲明:struct is_template;   
#endif   




//模板特化(調用時需指定,但特殊情況特殊處理)   
template<>  
struct is_template<int, char>{ enum { value = 1}; };   


//模板偏特化(調用時需指定,但部份特殊處理)   
template <class T1, class T2>  
struct is_template<T1*, T2>{ enum { value = 2}; };  


//模板偏特化(調用時需部份指定)   
template <class T2>  
struct is_template<char, T2>{ enum { value = 3}; };  


//模板實例化(調用時無需指定了)   
struct is_template_ex : public  is_template<int, char>      
{  
enum { value = 4};  
};  


//偏特化還可以用於具體數值
template <class T, int index>  
struct is_template_value{ enum { value = 11}; };
//參數爲0時的偏特化
template <class T>  
struct is_template_value<T, 0>{ enum { value = 22}; };  




//偏特化還可以用於類型配對
template <class T1, class T2>
struct find_type
{
enum { value = -1 };
};
template <class T> //類型相等時的偏特化
struct find_type<T, T>
{
enum { value = 0 };
};






void main()  
{  


cout<<is_template<int,bool>::value<<endl;  
cout<<is_template<int,char>::value<<endl;  
cout<<is_template<int*,char>::value<<endl;  
cout<<is_template<char,int>::value<<endl;  
cout<<is_template_ex::value<<endl;  


cout<<is_template_value<int,5>::value<<endl;  
cout<<is_template_value<int,0>::value<<endl;  


cout<<find_type<int,char>::value<<endl;  
cout<<find_type<int,int>::value<<endl;  
cout<<find_type<char,char>::value<<endl;  


int k;
cin>>k;
if( 0 == k)
{
cout<<find_type<char,int>::value<<endl;  
}
else
{
cout<<find_type<char,char>::value<<endl;  
}



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