关于c++:typetraits源码阅读笔记

63次阅读

共计 1574 个字符,预计需要花费 4 分钟才能阅读完成。

// enable_if
template <bool, typename _Tp = void>
struct enable_if {};

template <typename _Tp>
struct enable_if<true, _Tp>
{typedef _Tp type;}

// integral_constant
template<typename _Tp, _Tp __v>
struct integral_constant
{
  static constexpr _Tp                  value = __v;
  typedef _Tp                           value_type;
  typedef integral_constant<_Tp, __v>   type;
  constexpr value_type operator()() const noexcept {return value;}
};

/// The type used as a compile-time boolean with true value.
typedef integral_constant<bool, true>     true_type;

/// The type used as a compile-time boolean with false value.
typedef integral_constant<bool, false>    false_type;

<type_traits> 值得好好读

  1. 第一局部,定义了 integral_constant 以及

    * Template utilities for compile-time introspection and modification,
    * including type classification traits, type property inspection traits
    * and type transformation traits.
    using true_type = integral_constant<bool, true>;
    using false_type = integral_constant<bool, false>;

    定义默认模板类继承 false_type,而后对符合要求的内建类型进行偏特化,继承 true_type

    同时一些也利用了可变模板参数(如 conditional andor

  2. 第二局部,定义了 destructibleconstructible type properties.

    * Utility to simplify expressions used in unevaluated operands
    * declval is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed.
    declval 在不结构对象(不求值的状况下返回成员函数的返回值)

    这一部分用于判断是否可结构 / 析构,那么肯定波及判断是否含有结构 / 析构函数,这为咱们判断某个类是否存在某个函数提供了思路。假如要判断的函数是 testfunc()

    class true_type{};
    class false_type{};
    
    struct _has_testfunc_impl{template <typename _Tp, typename = decltype(std::declval(_Tp)().testfunc())>
            static true_type __test(int);
        template <typename>
            static false_type __test(...);
    }
    
    template<typename _Tp>
    struct has_testfunc : public _has_testfunc_impl
    {using type = decltype(__test<_Tp>(0));
    }

正文完
 0