源码如下:

  template<typename>
struct __is_pointer_helper
: public false_type { }; template<typename _Tp>
struct __is_pointer_helper<_Tp*>
: public true_type { }; /// is_pointer
template<typename _Tp>
struct is_pointer
: public integral_constant<bool, (__is_pointer_helper<typename
remove_cv<_Tp>::type>::value)>
{ };

首先,定义了两个类型,一个true_type和一个false_type这两个值均继承integral_constant。这两个类型几乎被所有的is_xxx复用啦。而且标准库也提供给我们使用。

然后,模板偏特化,指针类型的版本继承true_type,非指针类型的版本继承了false_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 operator value_type() { return value; }
}; template<typename _Tp, _Tp __v>
constexpr _Tp integral_constant<_Tp, __v>::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;
template<typename>
struct __is_member_function_pointer_helper
: public false_type { }; template<typename _Tp, typename _Cp>
struct __is_member_function_pointer_helper<_Tp _Cp::*>
: public integral_constant<bool, is_function<_Tp>::value> { }; /// is_member_function_pointer
template<typename _Tp>
struct is_member_function_pointer
: public integral_constant<bool, (__is_member_function_pointer_helper<
typename remove_cv<_Tp>::type>::value)>
{ };

成员指针,稍微复杂一点,和一般指针类似,成员指针的偏特化要写成这样_Tp _Cp::*。

 // Primary template.
/// Define a member typedef @c type to one of two argument types.
template<bool _Cond, typename _Iftrue, typename _Iffalse>
struct conditional
{ typedef _Iftrue type; }; // Partial specialization for false.
template<typename _Iftrue, typename _Iffalse>
struct conditional<false, _Iftrue, _Iffalse>
{ typedef _Iffalse type; };

conditional机制类似于loki中的Select,根据boolean值来选择类型,如果_Cond为true,则选择_Iftrue类型,否则选择另一个。

  /// is_reference
template<typename _Tp>
struct is_reference
: public __or_<is_lvalue_reference<_Tp>,
is_rvalue_reference<_Tp>>::type
{ };

is_reference通过or结合左值引用和右值引用判断。

 template<typename...>
struct __or_; template<>
struct __or_<>
: public false_type
{ }; template<typename _B1>
struct __or_<_B1>
: public _B1
{ }; template<typename _B1, typename _B2>
struct __or_<_B1, _B2>
: public conditional<_B1::value, _B1, _B2>::type
{ }; template<typename _B1, typename _B2, typename _B3, typename... _Bn>
struct __or_<_B1, _B2, _B3, _Bn...>
: public conditional<_B1::value, _B1, __or_<_B2, _B3, _Bn...>>::type
{ };

1.or继承conditional所提供的类型而不是conditional本身。

2.conditional通过or中第一类型boolean来提供不同的类型,如果B1的boolean是true则继承(也表明B1继承了true_type),不是则继承剩余参数or(递归继承下去)。

3.递归下去,就剩下一个类型时,则直接继承B1,B1的boolean就是整个or的结果

4.递归到末尾空参数,继承false_type,整个or的结果即为false。

05-27 18:13