【问题标题】:Why can't co_await return a string?为什么 co_await 不能返回字符串?
【发布时间】:2021-08-23 20:30:58
【问题描述】:
#include <coroutine>
#include <string>

template<typename T>
struct Awaiter final {
    bool await_ready() const { return false; }    
    void await_suspend(std::coroutine_handle<>) const {}    
    T await_resume() const { return T{}; }
};

struct ReturnObject {
  struct promise_type {
    ReturnObject get_return_object() { return {}; }
    std::suspend_never initial_suspend() 
        noexcept { return {}; }
    std::suspend_never final_suspend() 
        noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
  };
};

ReturnObject f()
{
    auto a1 = Awaiter<int>{};
    [[maybe_unused]] auto v1 = co_await a1; // ok    
    auto a2 = Awaiter<std::string>{};
    [[maybe_unused]] auto v2 = co_await a2; // error
}

int main() { f(); }

见:online demo

错误信息:

error: no suspend point info for ''co_await' not supported 
       by dump_decl<declaration error>'
   37 |     [[maybe_unused]] auto v2 = co_await a2; // error
      |                                ^~~~~~~~

为什么 co_await 不能返回字符串?

【问题讨论】:

    标签: c++ gcc compiler-errors c++20 coroutine


    【解决方案1】:

    这是 GCC 中协程实现中的一个编译器错误,因为在当前标准草案中没有任何内容禁止 await_resume 的自定义/复合类型(当用任何用户定义的类型替换字符串时可以看到)。 相同的代码,例如 compiles 和最新版本的 MSVC 使用 /std:c++latest 标志(这并不奇怪,因为 Gor Nishanov 是草稿的主要开发者,他使用 Visual Studio 来实现一个原型,这可能是最在撰写此答案时经过测试的实现)。

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 2013-04-02
      • 2020-07-06
      • 2018-09-17
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多