boost::type_traits

与STL的实现不同 在boost中 他们使用的是模板片特化来实现的type traits
基本思想就是 默认大部分都不支持某种特性 然后 当某个类型支持时就为他特化一个类 支持这样的特性
感觉这样写的话 在特化的时候会不会代码会比较多呢 ...
具体就是
template<typename T>
class something
{
// 在这里写对广大的类的操作
}

然后对于特殊的类型 譬如说 int
template<>
class something<int>
{
//然后在这里写对Int做的特殊的操作
}

而为了type traits来说 它的特殊操作就是在泛型类里面做一个枚举 值为false而在 int里面这个值为true
那么 当算法来用这个对象时 可以根据这个枚举的值来选择相应的算法 ,譬如对int的速度比较快的 或者对泛型的正确的算法

下面是 std::swap的一个优化版本

//
// iter_swap:
// tests whether iterator is a proxying iterator or not, and
// uses optimal form accordingly:
//
namespace detail{
template <typename I>
static void do_swap(I one, I two, const boost::false_type&)
{
    typedef typename std::iterator_traits<I>::value_type v_t;
    v_t v = *one;
    *one = *two;
    *two = v;
}
template <typename I>
static void do_swap(I one, I two, const boost::true_type&)
{
    using std::swap;
    swap(*one, *two);
}
}

template <typename I1, typename I2>
inline void iter_swap(I1 one, I2 two)
{
    //
    // See is both arguments are non-proxying iterators,
    // and if both iterator the same type:
    //
    typedef typename std::iterator_traits<I1>::reference r1_t;
    typedef typename std::iterator_traits<I2>::reference r2_t;
    typedef boost::integral_constant<bool,
    ::boost::is_reference<r1_t>::value
        && ::boost::is_reference<r2_t>::value
        && ::boost::is_same<r1_t, r2_t>::value> truth_type;

    detail::do_swap(one, two, truth_type());
}

其中 boost::integral_constant<bool, ::boost::is_reference<r1_t>::value
        && ::boost::is_reference<r2_t>::value
        && ::boost::is_same<r1_t, r2_t>::value> truth_type
就是一个枚举 看传入的参数是否可以用std::swap 如果可以则连接到std::swap不然就用自己写的 呵呵 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值