【问题标题】:Deducing type of template parameter expression推导模板参数表达式的类型
【发布时间】:2017-03-23 02:28:54
【问题描述】:

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

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 应该返回 A&lt;float&gt;()(因为将 integerfloat 相加得到 float)。

【问题讨论】:

    标签: c++ templates arithmetic-expressions type-deduction


    【解决方案1】:

    您可以使用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>();
      }
    };
    

    【讨论】:

      【解决方案2】:

      您可以将decltypestd::declval 一起使用:

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

      decltype 为您提供表达式的类型。 std::declval 创建一个对某个类型的引用,用于在 decltype 表达式中使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-15
        相关资源
        最近更新 更多