从true值到std::true_type的隐式转换

Implicit conversion from true value to std::true_type

本文关键字:true 转换 值到 std type      更新时间:2023-10-16

这是我为研究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;
}

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

我想知道零件is_integral<T>()是如何工作的?

我在读这篇文章:http://en.cppreference.com/w/cpp/types/is_integral我找不到任何关于这种行为的具体描述-没有operator() 的定义

is_integral<T>是继承自true_typefalse_type的类型。

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