首页 > 代码库 > 模板特化

模板特化

template<class T>class Compare{public:    static bool IsEqual(const T& lh, const T& rh)    {        return lh == rh;    }};
View Code

1) 特化为绝对类型

     int i1 = 10;     int i2 = 10;     bool r1 = Compare<int>::IsEqual(i1,i2);
View Code

2) 特化为引用,指针类型

int* p1 = &i1;int* p2 = &i2;bool r4 = Compare<int*>::IsEqual(p1,p2);
View Code

3) 特化为另外一个类模板

vector<int> v1;v1.push_back(1);v1.push_back(2);vector<int> v2;v2.push_back(1);v2.push_back(2);bool r5 = Compare<vector<int> >::IsEqual(v1, v2);
View Code

 

类模板全特化和偏特化

template<typename T1, typename T2>  class Test  {  public:      Test(T1 i,T2 j):a(i),b(j){cout<<"模板类"<<endl;}  private:      T1 a;      T2 b;  };    template<>  class Test<int , char>  {  public:      Test(int i, char j):a(i),b(j){cout<<"全特化"<<endl;}  private:      int a;      char b;  };    template <typename T2>  class Test<char, T2>  {  public:      Test(char i, T2 j):a(i),b(j){cout<<"偏特化"<<endl;}  private:      char a;      T2 b;  };  
View Code

函数模板置支持全特化

//模板函数   template<typename T1, typename T2>  void fun(T1 a , T2 b)  {      cout<<"模板函数"<<endl;  }    //全特化   template<>  void fun<int ,char >(int a, char b)  {      cout<<"全特化"<<endl;  }    //函数不存在偏特化:下面的代码是错误的   /* template<typename T2> void fun<char,T2>(char a, T2 b) {     cout<<"偏特化"<<endl; } */  
View Code

 

模板特化