C++/is_integral_v 实现解读 折叠表达式
C++ 标准17 折叠表达式的学习
源码如下:其中调用了 _Is_any_of_v
_EXPORT_STD template <class _Ty> _INLINE_VAR constexpr bool is_integral_v = _Is_any_of_v<remove_cv_t<_Ty>, bool, char, signed char, unsigned char, wchar_t, #ifdef __cpp_char8_t char8_t, #endif // __cpp_char8_t char16_t, char32_t, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long>;
其中:_Is_any_of_v 调用:
template <class _Ty, class... _Types> _INLINE_VAR constexpr bool _Is_any_of_v = // true if and only if _Ty is in _Types disjunction_v<is_same<_Ty, _Types>...>;
disjunction_v 实现代码:
template <bool _First_value, class _First, class... _Rest> struct _Disjunction { // handle true trait or last trait using type = _First; }; template <class _False, class _Next, class... _Rest> struct _Disjunction<false, _False, _Next, _Rest...> { // first trait is false, try the next trait using type = typename _Disjunction<_Next::value, _Next, _Rest...>::type; }; _EXPORT_STD template <class... _Traits> struct disjunction : false_type {}; // If _Traits is empty, false_type template <class _First, class... _Rest> struct disjunction<_First, _Rest...> : _Disjunction<_First::value, _First, _Rest...>::type { // the first true trait in _Traits, or the last trait if none are true };
主要使用了偏特化,与折叠表达式特性
修改如下:
template<bool bHas, class First, class... Rest> struct hasInclude2 { using type = First; }; /// 这里明确递归使用,偏特化处理
/// 理解的难点是偏特化 template<class First, class Next, class... Rest> struct hasInclude2<false, First, Next, Rest...> : hasInclude2<Next::value, Next, Rest...>{}; template<class First,class... Rest> struct hasInclude1 : hasInclude2<First::value,First,Rest...>{ }; template<class T, class... Rest> struct hasInclude : hasInclude1<std::is_same<T, Rest>...>{};
bool bChar = hasInclude<char,char,int,long>::type::value;