type_traits源码阅读笔记

// enable_if
template 
struct enable_if {};

template 
struct enable_if
{ typedef _Tp type; }

// integral_constant
template
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     true_type;

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

值得好好读

  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;
    using false_type = integral_constant;

    定义默认模板类继承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 
            static true_type __test(int);
        template 
            static false_type __test(...);
    }
    
    template
    struct has_testfunc : public _has_testfunc_impl
    {
        using type = decltype(__test<_Tp>(0));
    }

你可能感兴趣的:(c++)