源碼如下:
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。
1 /// integral_constant
2 template<typename _Tp, _Tp __v>
3 struct integral_constant
4 {
5 static constexpr _Tp value = __v;
6 typedef _Tp value_type;
7 typedef integral_constant<_Tp, __v> type;
8 constexpr operator value_type() { return value; }
9 };
10
11 template<typename _Tp, _Tp __v>
12 constexpr _Tp integral_constant<_Tp, __v>::value;
13
14 /// The type used as a compile-time boolean with true value.
15 typedef integral_constant<bool, true> true_type;
16
17 /// The type used as a compile-time boolean with false value.
18 typedef integral_constant<bool, false> false_type;
19 template<typename>
20 struct __is_member_function_pointer_helper
21 : public false_type { };
22
23 template<typename _Tp, typename _Cp>
24 struct __is_member_function_pointer_helper<_Tp _Cp::*>
25 : public integral_constant<bool, is_function<_Tp>::value> { };
26
27 /// is_member_function_pointer
28 template<typename _Tp>
29 struct is_member_function_pointer
30 : public integral_constant<bool, (__is_member_function_pointer_helper<
31 typename remove_cv<_Tp>::type>::value)>
32 { };
成員指針,稍微復雜一點,和一般指針類似,成員指針的偏特化要寫成這樣_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。