Question

This is a simple template progs that I wrote to study C++:

#include <type_traits>
#include <iostream>

using namespace std;

template<typename T>
T foo(T t, true_type)
{
    cout << t << " is integral! ";
    return 2 * t;
}


template<typename T>
T foo(T t, false_type)
{
    cout << t << " ain't integral! ";
    return -1 * (int)t;
}

template<typename T>
T do_foo(T t){
    return foo(t, is_integral<T>());
}

int main()
{
    cout << do_foo<int>(3) << endl;
    cout << do_foo<float>(2.5) << endl;
}

It doesn't do anything to fancy, but it does compile and work.

I am wondering how does the part is_integral<T>() work?

I was reading this : http://en.cppreference.com/w/cpp/types/is_integral and I can't find any specific description of this behavior - no definition of operator()

Was it helpful?

Solution

is_integral<T> is a type that inherits either from true_type or false_type.

is_integral<T>() is a constructor call, so that an instance of one of those types is an argument to the call to foo. The overload is then selected according to which one it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top