Specialization of C++ Templates

Specializations of function templates

//必须有一个基础模板
template<typename T>
void add(T a, T b) {
    
    
    cout << "init template" << endl;
}

template<>
void add<int>(int a, int b) {
    
    
    cout << "special template" << endl;
}

int main() {
    
    
    add(2.1, 2.2);          //init template
    add(1, 3);              //special template
    add<int>(2.1, 2.2);     //special template
    return 0;
}

For special types that cannot be handled by function templates, an ordinary function of this type is generally defined, and function template specialization is rarely used, and function templates do not support partial specialization

Specializations of class templates

//特化之前需要存在基础类模板
template<typename T, typename U>
class A {
    
    
public:
    A() {
    
     cout << "init template" << endl; }
};

//偏特化: 部分特化
template<typename T>
class A<T, int> {
    
    
public:
    A() {
    
     cout << "part special template" << endl; }
};

//全特化: 所有的参数都为具体类型
template<>
class A<int, int> {
    
    
public:
    A() {
    
     cout << "all special template" << endl; }
};

int main() {
    
    
    A<int, int> a;            //all special template
    A<double, int> b;         //part special template
    A<double, double> c;      //init template
    return 0;
}

Priority level: full specialization > partial specialization > common template

Selection of Template Calls

template<class T, class U>   //原版类模板
class A {
    
    
public:
    A(T a, U b) : a(a), b(b) {
    
    
        cout << a + b << endl;
    }
    T a;
    U b;
};

template<class T>           //类模板的偏特化   必须在原版模板之后
class A<T, T> {
    
    
public:
    A(T a, T b) : a(a), b(b) {
    
    
        cout << a - b << endl;
    }
    T a, b;
};

/*********************************************************/

template<typename T>   //函数模板的(类似重载)  位置不受限制
void func(T a, T b) {
    
    
    cout << a - b << endl;
}

template<typename T, typename U>   //原版函数模板
void func(T a, U b) {
    
    
    cout << a + b << endl;
}

template<>                    //函数模板的全特化   必须在原版模板之后
void func(int a, int b) {
    
    
    cout << a * b << endl;
}


int main() {
    
    
    //匹配相似度最高的版本
    A<int, int> a(1, 1);  //0        
    func(1.0, 1.0);       //0
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_40342400/article/details/128307797