使用 decltype 的条件声明类型

conditional declaration of type using decltype

本文关键字:声明 类型 条件 decltype 使用      更新时间:2023-10-16

我认为条件类型可以在模板函数中使用decltype来声明。但似乎不是。谁能指出我的测试代码有什么问题?

#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
#define print_type(var) do { 
std::cout << type_id_with_cvr<decltype(var)>().pretty_name() << std::endl; 
} while(0)
template <typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(a < b ? b : a) {
decltype(a < b ? b : a) c = a < b ? b : a;
print_type(c);
return a < b ? b : a;
}
int main() {
int i = 10;
double d = 3.3;
decltype(i < d? d : i) r = i < d? d : i;
print_type(r); // -> double
std::cout << r << std::endl; // 10
}

我想你的意图

decltype( a < b ? a : b )

是获得b类型时a < b,否则获得a类型。

也就是说:我想您的意图是根据ab的运行时间值获得类型确定的运行时间

这在C++是不可能的,因为变量的类型必须在编译时决定。

有了这个decltype()你得到三元运算符的类型

a < b ? a : b

这不依赖于ab的值,而仅取决于它们的类型。

所以,在这种情况下

decltype(i < d? d : i)

其中iintddouble,你得到一个doubleid的值无关紧要。