利用模板判断模板参数类型
C++中可以把数据类型当成参数,类型参数可以由编译器推导出来,也可以由程序员显式指定.下面的两个模板,就可以用来判断模板的类型参数是否为reference或者const.template <typename T>struct IsReference///Use this struct to determine if a template type is a reference{enum {VALUE = 0};};
template <typename T>struct IsReference<T&>{enum {VALUE = 1};};
template <typename T>struct IsReference<const T&>{enum {VALUE = 1};};
template <typename T>struct IsConst///Use this struct to determine if a template type is a const type{enum {VALUE = 0};};
template <typename T>struct IsConst<const T&>{enum {VALUE = 1};};
template <typename T>struct IsConst<const T>{enum {VALUE = 1};};
这两个模板函数(IsReference和IsConst)聪明的地方在于,编译器会根据模板参数的类型,选择最贴近的模板类(struct)来实例化.
使用示例:template <typename T> void foo() { if (IsReferenc<T>.VALUE) { // 类型参数T为reference }if (IsConst<T>.VALUE) { // 类型参数为const } }
页:
[1]