ssss 1 2 3 3 4 45

[C++11/17]type_traits-conditional

type_traits

本文分析 c++ 标准库里关于conditional定义 的细节。

template<bool, typename, typename> struct conditional;

conditional通过传入的第一个参数,决定 type的类型

  • 如果 是true: type是第二个类型参数
  • 如果 是false: type是第三个类型参数

他的实现是这样的

在定义的时候默认 type指定为第二个类型 

template<bool _Cond, typename _Iftrue, typename _Iffalse>
    struct conditional
    { typedef _Iftrue type; };

 

 然后能过模板特化处理。对false的情况进行特别定义,把type 指定为第三个类型

  // Partial specialization for false.

template<typename _Iftrue, typename _Iffalse> struct conditional<false, _Iftrue, _Iffalse> { typedef _Iffalse type; };

 

综上:

    conditional的作用就是通过第一个参数 (trur/false),来决定type的类型。

    在实战的应用中。也主要是使用conditional的这个特点。来根据第一个参数获得conditional里的类型

    template typename conditional<_Cond, _Iftrue, _Iffalse>::type

    等价于下面的逻辑

    bool?_Ifture:Iffalse ==

 

    在c++17中对type的提取操作定义 了别名   conditional_t


  /// Alias template for conditional
template<bool _Cond, typename _Iftrue, typename _Iffalse> using conditional_t = typename conditional<_Cond, _Iftrue, _Iffalse>::type;

  

posted @ 2021-09-24 17:09  会游泳的骆驼  阅读(215)  评论(0)    收藏  举报
百度 123

没有一个人在这个世上独活。