gpt4 book ai didi

c++ - 从真值到 std::true_type 的隐式转换

转载 作者:太空狗 更新时间:2023-10-29 20:14:00 25 4
gpt4 key购买 nike

这是我为了学习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() 的定义

最佳答案

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

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

关于c++ - 从真值到 std::true_type 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com