如何通过模板限制类型

来源:互联网 发布:淘宝天猫评论采集工具 编辑:程序博客网 时间:2024/05/21 19:41

模板的作用是把一组不相关的数据类型作为通用型进行抽象,这样实现泛型。但反过来看如何限制类型呢比如我要限制char类型的生成。这个问题其实可以用模板特化实现。

#include<iostream>using namespace std;template<class T>class contan{};template<>class contan<char>{~contan();};template<class T>struct check{typedef T value;};template<>struct check<char>{};template<class T>void fun(){contan<T> c;typedef check<T>::value value;}int main(){fun<char>();}
当调用char类型时,contan会调用私有的析构编译不通过,而check则没有定义value 

0 0
原创粉丝点击