美文网首页
C++模板的特化与偏特化

C++模板的特化与偏特化

作者: 阿布554_ | 来源:发表于2017-09-01 10:43 被阅读11次
//类模板特化
template <class T>
class A{
public:
    A(){
        std::cout << "T" << std::endl;
    }
};
template <>
class A<int>{
public:
    A(){
        std::cout<<"int"<<std::endl;
    }
};
//函数模板特化
template <class T>
int compare(T t1,T t2){
    return t1<t2;
}
template <>
int compare(const char* t1,const char* t2){
    //strcmp 按位用ASCII表进行比较,大于和小于只规定返回正数和负数,并没有规定一定返回1和-1
    int flag = strcmp(t1,t2);
    return flag;
}
//类模板的偏特化
template <class Tb,class local_allocator>
class container{
public:
    container(){
        std::cout << "general" << std::endl;
    }
};

template <class local_allocator>
class container<bool,local_allocator>{
public:
    container(){
        std::cout << "specialize" << std::endl;
    }
};

按我自己的理解(可能不太准确),偏特化意思就是讲原来的某个特化类型替换为具体类型

int main() {
    A<int> a;
    A<double> b;
    container<int ,int> c;
    container<bool,int> d;
    std::string str1 = "qwer";
    std::string str2 = "dfffff";
    std::cout << compare(str1.c_str(),str2.c_str())<<std::endl;
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

输出结果为

image.png

相关文章

网友评论

      本文标题:C++模板的特化与偏特化

      本文链接:https://www.haomeiwen.com/subject/lsuhjxtx.html