如何实现std :: is_integral?

时间:2017-04-23 13:46:24

标签: c++11 templates typetraits

我不熟悉cpp中的模板魔法。看完了什么' TemplateRex'在link中说,我对std :: is_intergral的工作原理感到困惑。

template< class T >
struct is_integral
{
    static const bool value /* = true if T is integral, false otherwise */;
    typedef std::integral_constant<bool, value> type;
};

我可以理解SFINAE的工作原理以及特征的工作原理。在引用cppreference之后,实现&#39; is_pointer&#34;被发现而不是&#39; is_integral&#39;看起来像这样:

template< class T > struct is_pointer_helper     : std::false_type {};
template< class T > struct is_pointer_helper<T*> : std::true_type {};
template< class T > struct is_pointer : is_pointer_helper<typename std::remove_cv<T>::type> {};

&#39; is_integral&#39;有类似的实施?怎么样?

1 个答案:

答案 0 :(得分:6)

here我们得到了:

  

检查T是否为整数类型。提供成员常量值,该值等于true,如果T是bool类型,charchar16_tchar32_twchar_t,{{1} },shortintlong或任何实现定义的扩展整数类型,包括任何有符号,无符号和cv限定的变体。否则,value等于false。

这样的事情可能就是你可以实现它的方式:

long long

请注意,template<typename> struct is_integral_base: std::false_type {}; template<> struct is_integral_base<bool>: std::true_type {}; template<> struct is_integral_base<int>: std::true_type {}; template<> struct is_integral_base<short>: std::true_type {}; template<typename T> struct is_integral: is_integral_base<std::remove_cv_t<T>> {}; // ... std::false_typestd::true_type的特化。有关详细信息,请参阅here

相关问题