【问题标题】:error: `type` in `class std::result_of` does not name a type错误:`class std::result_of` 中的`type` 没有命名类型
【发布时间】:2018-11-08 17:53:28
【问题描述】:

下面的示例在我尝试过的所有编译器中都失败了:gcc-8.2、clang-8.0(--std=c++17std=c++2a 都已尝试)和 zapcc-2017.08。

在我看来,代码示例是有效的,应该被编译。或者,至少,应该有一个更全面的错误。它看起来确实像 std 库中的一个错误,没有涵盖 result_of 的这种特殊情况。我错了吗?

#include <type_traits>
using namespace std;
struct bar {
    int a;
    long b;
};

template<auto M>
struct foo {
    static auto q(bar & b) {
        return b.*M;
    }
};

template<auto M>
auto qoo(bar & b) {
    return b.*M;
}


// error: 'type' in 'class std::result_of<int(bar&)>' does not name a type
using f = typename result_of<decltype(foo<&bar::a>::q)>::type;
// error: 'type' in 'class std::result_of<int(bar&)>' does not name a type
using q= typename result_of<decltype(qoo<&bar::a>)>::type;

【问题讨论】:

  • result_of 的 cppreference 文档下列出的任何怪癖是否回答了您的问题?
  • @πάνταῥεῖ 您处于 C++11 模式,这使得它因完全不同的原因而失败。将其置于 C++17 模式,您将获得与 OP 相同的输出。
  • @LightnessRacesinOrbit 哎呀yes.
  • @Lightness Races in Orbit - 五个都没有列出

标签: c++ templates c++17 c++20 result-of


【解决方案1】:

result_of_t&lt;F(Args...)&gt; 表示“使用Args... 调用/调用F 的结果”。

result_of_t&lt;int(bar&amp;)&gt; 表示“用bar&amp; 调用int 的结果”。这不存在,因为你不能用任何东西调用int

result_of 不是“从函数类型中提取返回类型”。

【讨论】:

    【解决方案2】:

    试试

    using f = typename std::result_of<decltype(&foo<&bar::a>::q)(bar&)>::type;
    
    using q= typename std::result_of<decltype(&qoo<&bar::a>)(bar&)>::type;
    

    正如 T.C. 更好地解释的那样,std::result_of 中的 type 是使用某些参数类型调用时从可调用类型返回的类型。

    如果你写

    std::result_of<decltype(foo<&bar::a>::q)>
    

    您只将可调用的类型传递给std::result_of(几乎:在foo 之前还需要一个&amp;);您还必须传递参数的类型(只有一个参数,在这种情况下:bar 引用),所以

    std::result_of<decltype(&foo<&bar::a>::q)(bar&)>
    

    【讨论】:

      【解决方案3】:

      根据我的经验,result_of 确实没有什么可以做到而decltype 不能(或result_of_t 这将有助于简化您的代码):How Can I Use result_of Instead of decltype?

      在这种情况下也是如此,decltypedeclval 将提供比 result_of 更简单的结果:

      using f = decltype(foo<&bar::a>::q(declval<bar&>()));
      using q = decltype(qoo<&bar::a>(declval<bar&>()));
      

      Live Example

      【讨论】:

      • result_of 是必要的,如果你想支持所有的可调用对象。
      • @T.C.我想不出一个我不能使用declvaldecltype的组合来实现的例子,但我想理解。我应该再问一个问题,还是您可以在评论中给出一个简单的例子?
      • 所有可调用对象包括指向成员的指针。
      • @T.C.我不能使用declval 调用指向成员的指针吗?例如:ideone.com/25wpKD
      • 当然。现在尝试编写一个适用于 both 指向成员 函数对象的指针。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多