【问题标题】:std::result_of for built-in operators内置运算符的 std::result_of
【发布时间】:2014-12-16 18:06:45
【问题描述】:

通过result_of 确定-int()double()*double() 之类的结果的正确语法是什么?

失败了

std::result_of<operator-(int)>::type
std::result_of<operator*(double,double)>::type

【问题讨论】:

  • 您可以改用decltype
  • @b4hand typename 只有在传递给模板的参数依赖于模板参数时才需要。 intdouble 不依赖。

标签: c++ c++11 typetraits


【解决方案1】:

std::result_of 真的不是在这里采取的方法。 decltype 正是你想要的,可以用作decltype(-int())decltype(double()*double()) 等。如果你不知道该类型是否是默认可构造的,你也可以使用std::declvaldecltype(-std::declval&lt;int&gt;())

任何涉及operator- 的语法都不起作用的原因是operator- 语法仅适用于自定义重载运算符。内置运算符没有任何可引用的支持函数。

【讨论】:

    【解决方案2】:

    decltype绝对是这里的路,但是如果一定要使用result_of,可以使用&lt;functional&gt;中定义的function objects来完成

    例如,要获得double * double 的结果类型,请使用

    std::result_of<std::multiplies<double>(double, double)>::type
    

    同样,一元否定是

    std::result_of<std::negate<int>(int)>::type
    

    使用 C++14,您甚至可以查询两种不同类型的数学运算的结果类型

    std::result_of<std::plus<>(double, int)>::type
    

    当然,同样的技术也可以用于用户定义的类型

    struct foo{};
    struct bar{};
    bar operator/(foo, foo) { return bar{}; }
    
    std::result_of<std::divides<>(foo, foo)>::type
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2011-02-10
      • 1970-01-01
      • 2013-01-29
      相关资源
      最近更新 更多