使用decltype的类型的条件声明

问题描述 投票:1回答:1

我认为条件类型可以在模板函数中使用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
}
c++ c++11 templates decltype
1个回答
3
投票

我想你的意图

decltype( a < b ? a : b )

ba < b的类型否则,获得a的类型。

那就是:我想你的意图是根据ab的欠幅时间值获得一个确定的运行时间类型。

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

使用decltype(),您可以获得三元运算符的类型

a < b ? a : b

这不取决于ab的值,而只取决于它们的类型。

所以,在这种情况下

decltype(i < d? d : i)

其中iintddouble,你获得doubleid的值是无关紧要的。

© www.soinside.com 2019 - 2024. All rights reserved.