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

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

#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 不能返回字符串?

最佳答案

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

关于c++ - 为什么 co_await 不能返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67860049/

相关文章:

C++ 仿函数和模板 : error: declaration of 'class List<T>'

c - clang 和 gcc 是否为给定的结构定义生成相同的内存布局?

c++ - 不同文件夹中不同 .cpp 文件的 Makefile

c++ - 错误 : expected ‘}’ at end of input

c++ - 如何仅在值高于或低于特定阈值时读取数据

c++ - 将成员函数指针作为参数传递?问答

c++ - 包含 boost::numeric::ublas::matrix 的类的运算符重载

python - 使用 MS C 与 MinGW 编译 Python 的速度差异

c++ - 为什么我会收到此错误, 'method' 的左边必须有类/结构/union ?

c++ - 为什么VC++编译器使用boost\range\iterator.hpp