如何实现std :: is_integral?

问题描述 投票:8回答:1

我不熟悉cpp中的模板魔法。在阅读了这个link中的'TemplateRex'之后,我对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的工作原理以及特征的工作原理。在引用qazxsw poi之后,发现'is_pointer'的实现而不是'is_integral',它看起来像这样:

cppreference

'is_integral'有类似的实现吗?怎么样?

c++11 templates typetraits
1个回答
6
投票

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> {}; 我们得到:

检查T是否为整数类型。提供成员常量值,该值等于true,如果T是hereboolcharchar16_tchar32_twchar_tshortintlong或任何实现定义的扩展整数类型,包括任何有符号,无符号和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的特化。有关详细信息,请参阅std::integral_constant

© www.soinside.com 2019 - 2024. All rights reserved.