3

这是我为学习 C++ 而写的一个简单的模板 progs:

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

它没有做任何花哨的事情,但它确实可以编译和工作。

我想知道这部分是如何is_integral<T>()工作的?

我在读这个:http ://en.cppreference.com/w/cpp/types/is_integral ,我找不到这种行为的任何具体描述——没有定义operator()

4

1 回答 1

7

is_integral<T>是继承自true_type或的类型false_type

is_integral<T>()是构造函数调用,因此其中一种类型的实例是调用的参数foo。然后根据它是哪一个来选择过载。

于 2013-08-22T10:17:58.677 回答