// 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));
    }

七月流火
1 声望1 粉丝