Search code examples
c++stlc++17type-traits

How to use bool member function in is_integral_v?


From this cppreference link, is_integral has bool as a member function. How to use it? I could understand other members, and am able to code a simple example as follows. But how to use the bool member function?

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

int main(){
    cout << boolalpha;
    // member constants
    cout << is_integral_v<int> << endl; // prints true

    // member functions
    // operator bool ?
    
    // operator()
    cout << is_integral<float>() << endl; // prints false

    return 0;
}

Solution

  • When you call is_integral<float>(), you are actualy calling the operator bool. The following calls the operator() instead:

    is_integral<float>()()
    

    It can be seen more clear in the following code:

        std::is_integral<int> x;
        if (x) { // operator bool
            std::cout << "true" << std::endl;
        }
        std::cout << x << std::endl;  // operator bool
        std::cout << x() << std::endl; // operator()
        std::cout << std::is_integral<int>()() << std::endl; // operator()
    

    std::is_integral<float>() is actually an anonymous object of type std::is_integral<float>.