【问题标题】:why std::is_integral considers bool type as integral为什么 std::is_integral 将 bool 类型视为整数
【发布时间】:2021-09-17 06:34:48
【问题描述】:

在 C++ 类型特征中 std::is_integral<T>::value 返回 true,即使 T 是布尔值,根据其描述是正确的。

但是,如果 bool 是不同于其他整数类型的类型,为什么在这种情况下将其视为整数类型? 为什么我们没有单独的 std::is_boolean 类型特征?

#include <iostream>
#include <type_traits>

int main()
{
    std::cout << std::boolalpha;

    std::cout << std::is_same<int, bool>::value << ' '; // ~ false
    std::cout << std::is_same<unsigned int, bool>::value << ' '; // ~ false
    std::cout << '\n';
    std::cout << std::is_integral<bool>::value << ' '; // ~ true
    return 0;
}

【问题讨论】:

  • 您可以通过is_same 测试布尔值。为什么要为 bool 添加特殊特征? bool 与其他积分有何不同?只是位数不同。
  • 我很确定bool 是一个整数类型。 "Integral type" != 与 int / unsigned int 相同,您似乎正在检查。
  • 为什么bool 不是整数类型? longchar 也是与 int 不同的积分类型。为什么我们没有特殊特征is_charis_long?作为一个整体类型和作为一个int 是两个不同的东西。
  • @463035818_is_not_a_number 在数学中可悲的是,这可能是一个更常见的定义。这真的应该被称为std::is_fundamental/essential 或者更清楚的东西,因为编程中的“整数”是模棱两可的,因为 C++ 有整数类型,但也有整数类型。 en.cppreference.com/w/cpp/language/…
  • basic.fundamental: "bool、char、wchar_t、char8_t、char16_t、char32_t 类型以及有符号和无符号整数类型 [...] 统称为整数类型。整数类型的同义词是整数类型。”

标签: c++ c++11 typetraits


【解决方案1】:

它是一个整数类型,因此它可以出现在 Integral Constant Expressions 中。这在编写模板时非常重要——truefalse 通常用作非类型模板参数。

【讨论】:

    【解决方案2】:

    bool 是一位整数类型。整数类型有很多——intlonglong longstd::uint32_t

    bool 是一个整数类型这一事实可以追溯到 C++ 的开始,甚至可以追溯到 C,其中1 == 0 返回一个整数。

    如果要检测bool,请使用is_same&lt;T, bool&gt;

    很容易出现一种类似于 C++ 的语言,其中 bool 不是不可分割的。但这不是 C++。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2021-11-29
      • 2012-10-19
      • 2018-02-17
      • 2017-05-10
      相关资源
      最近更新 更多