全特化与偏特化

全特化与偏特化

1、普通类模板

template<class T,class N> 
class Template{}; 

2、全特化。

template<> 
class Template<int,char>{};

3、偏特化。

template<class T> 
class Template<T,int>{};

4、函数模板只能全特化,不能偏特化。

5、一个示例。

#include <iostream>
using namespace std;

template<typename T, typename N>
class Test
{
public:
    Test( T i, N j ) : a(i), b(j)
    {
        cout<<"普通模板类"<< a <<' ' << b << endl;
    }
private:
    T a;
    N b;
};

template<>
class Test<int , char>
{
public:
    Test( int i, char j ) : a( i ), b( j )
    {
        cout<<"模版类全特化"<< a  << ' ' << b << endl;
    }
private:
    int a;
    char b;
};

template <typename N>
class Test<char, N>
{
public:
    Test( char i, N j ):a( i ), b( j )
    {
        cout<<"模版类偏特化"<< a<< ' ' << b << endl;
    }
private:
    char a;
    N b;
};

//模板函数  
    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; 
// } 


int main()
{
    Test<double , double> t1( 0.1,0.2 );   //普通模版类
    Test<int , char> t2( 1, 'A' );   //模版类完全特化
    Test<char, bool> t3( 'A', true );  //模版类偏特化
    return 0;
}
原文地址:https://www.cnblogs.com/tekkaman/p/10183456.html