C++template元编程学习心得-switch结构

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函数的不完全的实现的啦,不过大体的意思已经到了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值