C++ template元编程–switch结构
swtich结构在template中的实现很简单,但是用途确实很广泛的啦!
首先我们来看看switch结构在template中一般都长什么样子
switch结构范本
//switch结构
//switch:
case1:
case2:
else:
template<class T>
struct dosomthing{}; //声明swtich的接口,并进行else分支
template<>
struct dosomething<T>{}; //进行实现,比如case1,或case2等等
例子
//作用,用来判断一个类型是不是int类型
template<class T>
struct is_int{
static bool value = false;
}; //声明一个template swtich的接口,并对else情况进行判断
template<>
struct is_int<int>{
static bool value = true;
};
更复杂的一个例子
//作用,用来把一个类型的constant去掉,得到一个不含constant的类型
template<class T> //声明接口,实现else分支
struct remove_constant{
typedef T type;
};
template<class T> //实现其他case的分支
struct remove_constant<const T>{
typedef T type;
};
template<class T> is_integral_impl;
//用来判断一个类型是不是整数
template<class T>
struct is_integral:is_intgral_impl<typename remove_constant<T>::type>{};
//此处将判断进行了转发,并且去掉了T可能带有的constant
//此处是真正进行判断的函数的声明和else分支实现
template<class T>
struct is_integral_impl{
static bool value = false;
};
//case:int
template<>
struct is_integral_impl<int>{
static bool value = true;
};
//case:long int
template<>
struct is_integral_impl<long int>{
static bool value = true;
};
//case: short
template<>
struct is_integral_impl<short>{
static bool value = true;
};
//case:char
template<>
struct is_integral_impl<char>{
static bool value = true;
};
看到了这里,有些朋友肯定会发现,其实,上面的给出的三个个template,实际上
就是C++ 11标准里面的type support函数的不完全的实现的啦,不过大体的意思已经到了.