为什么 std::is_integral 将 bool 类型视为整数

Rat*_*ari 6 c++ type-traits c++11

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

但是,如果 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;
}
Run Code Online (Sandbox Code Playgroud)

MSa*_*ers 4

它是整型,因此可以出现在整型常量表达式中。这在编写模板时非常重要 -true并且false通常用作非类型模板参数。