【问题标题】:How is std::is_integral implemented?std::is_integral 是如何实现的?
【发布时间】:2017-04-23 13:46:24
【问题描述】:

我不熟悉 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 的工作原理以及特征的工作原理。在引用cppreference 后,发现了“is_pointer”的实现,而不是看起来像这样的“is_integral”:

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> {};

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

【问题讨论】:

    标签: c++11 templates typetraits


    【解决方案1】:

    here 我们得到了:

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

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

    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_typestd::integral_constant 的特化。详情请见here

    【讨论】:

    • 您还需要删除 cv 限定符,因为 is_integral 需要为它们返回 true。以及处理有符号/无符号。
    • @NicolBolas 对,让我更新答案。谢谢。
    • std::integral_constant 的专业
    • @skypjack 实现定义的扩展整数类型怎么样?
    • @L.F.我很冷静,但我看不出这种改进有什么帮助。问题是std::is_integral 是如何实现的? 这里是一个考虑了几种类型来演示它的答案。您可能会争辩说我也没有考虑wchar_t,但添加它不会为答案本身添加任何内容。我的两分钱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2013-11-01
    • 1970-01-01
    • 2020-04-26
    • 2010-11-30
    相关资源
    最近更新 更多