推导模板参数表达式的类型

Deducing type of template parameter expression

如何推断模板参数表达式的类型?例如,关于以下代码:

template< typename T >
class A
{
//....
};

template< typename T_1, typename T_2 >
class B
{
  auto foo()
  {
    return A</* Type of "T_1+T_2"*/>();
  }
};

如何推导出T_1+T_2的类型?例如,它可以是 T_1=floatT_2=int,因此,foo 应该 return A<float>()(因为总结了一个 integerfloat 结果是 float).

您可以使用 decltype with std::declval:

return A<decltype(std::declval<T_1>() + std::declval<T_2>())>();

decltype 给出表达式的类型。 std::declval 突然创建一个类型的引用,用于 decltype 表达式。

您可以组合使用 decltypestd::declval。我还建议对结果类型进行 typedef 以提高可读性:

template< typename T_1, typename T_2 >
class B
{
  typedef decltype(std::declval<T_1>() + std::declval<T_2>()) result_type;
  auto foo() -> result_type
  {
    return A<result_type>();
  }
};