Home > Software design >  why std::is_integral considers bool type as integral
why std::is_integral considers bool type as integral

Time:09-22

In C type traits std::is_integral<T>::value returns true even if T is bool which is correct as per its description.

But if bool is a different type than other integral types, why its considered as integral type in this case? why we don't have a separate std::is_boolean type trait?

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

CodePudding user response:

It's an integral type so it can appear in Integral Constant Expressions. This is quite important when it comes to writing templates - true and false are commonly used as non-type template parameters.

CodePudding user response:

bool is a one bit integral type. There are many integral types -- int, long, long long, std::uint32_t.

The fact that bool is an integral type goes back to the start of C and even back to C, where 1 == 0 returns an integer.

If you want to detect bool, use is_same<T, bool>.

There could easily be a language much like C where bool isn't integral. But that isn't C .

  • Related