从协程产生值时发生错误“错误:成员引用基类型'void'不是结构或联合”

时间:2019-07-17 09:56:46

标签: c++ coroutine

我正在尝试使用实验性协程基元来构造简单的结构,但是当我尝试产生一个值时会出现错误

../main.cpp:6:5: error: member reference base type 'void' is not a structure or union
    co_yield "Hello";
#include <optional>
#include <experimental/coroutine>

template< typename T >
class Sequence {
public:
    static_assert( std::is_default_constructible_v<T> );
    static_assert( std::is_copy_constructible_v<T> || std::is_move_constructible_v<T> );

    struct promise_type {
        using coro_handle = std::experimental::coroutine_handle<promise_type>;

        auto get_return_object() {
            return coro_handle::from_promise( *this );
        }

        constexpr auto initial_suspend() {
            return std::experimental::suspend_always{};
        }

        constexpr auto final_suspend() {
            return std::experimental::suspend_always{};
        }

        auto yield_value( T&& value ) {
            this->value = value;
        }

        auto return_value( T&& value ) {
            this->value = value;
        }

        auto unhandled_exception() {
            exceptionPtr = std::current_exception(); // NOLINT(bugprone-throw-keyword-missing)
        }

        std::optional<T>   value;
        std::exception_ptr exceptionPtr;
    };

    using coro_handle  = std::experimental::coroutine_handle<promise_type>;

    Sequence( coro_handle handle ) : handle{ handle } { assert( handle ); } // NOLINT(google-explicit-constructor)

    Sequence( const Sequence& ) = delete;

    Sequence( Sequence&& ) noexcept = default;

    T operator()() {
        handle.resume();
        return get();
    }

    bool resume() {
        return handle.resume();
    }

    T get() {
        auto& promise = handle.promise();
        if ( promise.exceptionPtr )
            std::rethrow_exception( promise.exceptionPtr );
        return std::move( promise.value.value());
    }

private:
    coro_handle handle;
};

#include <iostream>
#include <string_view>

Sequence<std::string_view> foo(){
    co_yield "Hello";
    co_return "world";
}

int main() {
    auto c = foo();
    std::cout << c() << c() << '\n';
    return 0;
}

我尝试注释掉简历中的coro_handle的用法,只是返回true,注释掉get的正文并返回默认的构造对象,但是我遇到了同样的错误。

0 个答案:

没有答案