Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion from true value to std::true_type

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()

like image 490
Kiel Avatar asked Sep 20 '26 04:09

Kiel


1 Answers

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.

like image 71
Steve Jessop Avatar answered Sep 21 '26 18:09

Steve Jessop