C++ 函数/模板的偏特化和全特化

2021年03月30日 周二 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】


直接用代码来解释:

#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;
}

猜你喜欢

转载自blog.csdn.net/m0_37433111/article/details/115337085