【问题标题】:is_integral vs is_integer: is one of them redundant?is_integral vs is_integer:其中之一是多余的吗?
【发布时间】:2014-05-31 13:12:54
【问题描述】:

is_integralis_integer 似乎以同样的方式回答了同样的事情

从相关文档页面的链接中,is_integral 似乎缺少以下类型的专业化

signed char       
unsigned char     
unsigned short    
unsigned int      
unsigned long     
unsigned long long

然而,compiled example,(当然)也显示了它们在这些类型上的相同行为:

#include <iostream>
#include <type_traits>
using namespace std;

int main() 
{
    cout << is_integral<signed char       >::value << endl;
    cout << is_integral<unsigned char     >::value << endl;
    cout << is_integral<unsigned short    >::value << endl;
    cout << is_integral<unsigned int      >::value << endl;
    cout << is_integral<unsigned long     >::value << endl; 
    cout << is_integral<unsigned long long>::value << endl;
    return 0;
}

如果它们的行为也相同,那么在 C++11 中同时引入它们有什么意义?

如果它们的行为也相同,那么在 c++11 中引入它们有什么意义呢?

编辑:改写

正如Useless 指出的那样,is_integral 文档页面中的短语包括任何有符号、无符号和 cv 限定的变体表明,即使它们的规范也是完全匹配的。

【问题讨论】:

  • ...似乎缺少一些特化... - 你错过了句子 “包括任何有符号、无符号和 cv 限定的变体。” 在您的第一个链接页面中。
  • @Useless 是的,正确的。那就更糟了!

标签: c++ c++11 stl


【解决方案1】:

std::numeric_limits&lt;T&gt;::is_integer 不是 C++11 引入的。它刚刚更新为使用新的 constexpr 限定符。

std::is_integral&lt;T&gt; 是由 C++11 引入的,你是对的,它给出了相同的结果。至于为什么添加它 - 可能是因为类型的整体性或其他类型在逻辑上不是该类型 numeric_limits 的一部分?

&lt;type_traits&gt; 标头的目标似乎是将所有类型分类帮助器收集到一个位置,而较旧的 numeric_limits 仅收集特定于数字的属性。如果numeric_limits&lt;T&gt;::is_integer 被弃用,那么在&lt;type_traits&gt; 中存在哪些类型特征并且被认为是数字的会有一个稍微任意的边界。在两个地方都有它并不是一个可怕的重复。

【讨论】:

    【解决方案2】:

    两者是相同的,并且将提供相同的输出。

    但是 std::numeric_limits&lt;T&gt;::is_integer 自 C98 以来就存在,而不是 C++11,而 std::is_integral 是作为 C++11 类型特征的一部分引入的(&lt;type_traits&gt; 标头)

    编辑:

    正如@Useless 所提到的,引入std::is_integral 的原因可能是希望重新组合&lt;type_traits&gt; 中的所有特征。

    【讨论】:

      【解决方案3】:

      没有人提到 std::is_integral 遵循与其他 C++11 UnaryTypeTraits 相同的风格,即定义一个名为 value 的单个静态数据成员。这使得它可以在需要任何一元类型特征的地方互换使用,例如:

      template<typename Cond1, typename Cond2>
        using And = integral_constant<bool, Cond1::value && Cond2::value>;
      

      您不能以相同的方式使用std::numeric_limits::is_integer,因为它不遵循与 C++11 特征相同的约定。

      将每个 trait 拆分为具有一致名称的单一类型使它们比将多个属性与不可预知名称捆绑在一起的 trait 更灵活。

      【讨论】:

        【解决方案4】:

        Here's原提议将is_integral添加到C++0x。

        他们没有提到与std::numeric_limits&lt;&gt;::is_integer 的重叠,但我假设只是希望将所有类型特征放在一个明显的位置。

        【讨论】:

          猜你喜欢
          • 2013-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-07
          • 2018-04-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多