使用C++的template时,有时需要确定一个模板类是不是一个特定类型的,有时因为不用的类型需要不同的处理方式,这是可以考虑使用type traits
1.全特化:即所偶
#include<iostream>
template<typename T>
class is_int{
public:
static const bool value = false;
};
template<>
class is_int<int>{
public:
const static bool value= true;
};
int main(){
class is_int<int> iv_int;
std::cout << iv_int.value << std::endl;//iv_int是一个int实例化的类,所以打印true
class is_int<bool> iv_bool;
std::cout << iv_bool.value << std::endl;//iv_bool不是一个int实例化的类,所以答应false
}
注意:
声明特化模板之前一定要有非特化的声明!并且两个类的名字是一样的
模板的偏特化是指需要根据模板的某些但不是全部的参数进行特化
(1) 类模板的偏特化
例如c++标准库中的类vector的定义
template <class T, class Allocator>
class vector { // … // };
template <class Allocator>
class vector<bool, Allocator> { //…//};
这个偏特化的例子中,一个参数被绑定到bool类型,而另一个参数仍未绑定需要由用户指定。