命名空间
变体
操作

std::coroutine_traits

来自 cppreference.cn
< cpp‎ | 协程
 
 
 
协程支持
协程 traits
coroutine_traits
(C++20)
协程句柄
空操作协程
平凡可等待对象
范围生成器
(C++23)
 
定义于头文件 <coroutine>
template< class R, class... Args >
struct coroutine_traits;
(C++20 起)

从协程的返回类型和参数类型确定 promise 类型。标准库实现提供一个公开可访问的成员类型 promise_type,如果限定标识符有效并表示一个类型,则与 R::promise_type 相同。否则,它没有这样的成员。

coroutine_traits 的程序定义特化 必须定义一个公开可访问的嵌套类型 promise_type,否则程序是非良构的。

目录

[编辑] 模板参数

R - 协程的返回类型
Args - 协程的参数类型,包括隐式对象参数(如果协程是非静态成员函数)

[编辑] 嵌套类型

名称 定义
promise_type 如果有效,则为 R::promise_type,或由程序定义的特化提供

[编辑] 可能的实现

namespace detail {
template<class, class...>
struct coroutine_traits_base {};
 
template<class R, class... Args>
requires requires { typename R::promise_type; }
struct coroutine_traits_base <R, Args...>
{
    using promise_type = R::promise_type;
};
}
 
template<class R, class... Args>
struct coroutine_traits : detail::coroutine_traits_base<R, Args...> {};

[编辑] 注解

如果协程是非静态成员函数,则 Args... 中的第一个类型是隐式对象参数的类型,其余是函数的参数类型(如果有)。

如果 std::coroutine_traits<R, Args...>::promise_type 不存在或不是类类型,则相应的协程定义是非良构的。

用户可以定义 coroutine_traits 的显式或部分特化,依赖于程序定义的类型,以避免修改返回类型。

[编辑] 示例

#include <chrono>
#include <coroutine>
#include <exception>
#include <future>
#include <iostream>
#include <thread>
#include <type_traits>
 
// A program-defined type on which the coroutine_traits specializations below depend
struct as_coroutine {};
 
// Enable the use of std::future<T> as a coroutine type
// by using a std::promise<T> as the promise type.
template<typename T, typename... Args>
    requires(!std::is_void_v<T> && !std::is_reference_v<T>)
struct std::coroutine_traits<std::future<T>, as_coroutine, Args...>
{
    struct promise_type : std::promise<T>
    {
        std::future<T> get_return_object() noexcept
        {
            return this->get_future();
        }
 
        std::suspend_never initial_suspend() const noexcept { return {}; }
        std::suspend_never final_suspend() const noexcept { return {}; }
 
        void return_value(const T& value)
            noexcept(std::is_nothrow_copy_constructible_v<T>)
        {
            this->set_value(value);
        }
 
        void return_value(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
        {
            this->set_value(std::move(value));
        }
 
        void unhandled_exception() noexcept
        {
            this->set_exception(std::current_exception());
        }
    };
};
 
// Same for std::future<void>.
template<typename... Args>
struct std::coroutine_traits<std::future<void>, as_coroutine, Args...>
{
    struct promise_type : std::promise<void>
    {
        std::future<void> get_return_object() noexcept
        {
            return this->get_future();
        }
 
        std::suspend_never initial_suspend() const noexcept { return {}; }
        std::suspend_never final_suspend() const noexcept { return {}; }
 
        void return_void() noexcept
        {
            this->set_value();
        }
 
        void unhandled_exception() noexcept
        {
            this->set_exception(std::current_exception());
        }
    };
};
 
// Allow co_await'ing std::future<T> and std::future<void>
// by naively spawning a new thread for each co_await.
template<typename T>
auto operator co_await(std::future<T> future) noexcept
    requires(!std::is_reference_v<T>)
{
    struct awaiter : std::future<T>
    {
        bool await_ready() const noexcept
        {
            using namespace std::chrono_literals;
            return this->wait_for(0s) != std::future_status::timeout;
        }
 
        void await_suspend(std::coroutine_handle<> cont) const
        {
            std::thread([this, cont]
            {
                this->wait();
                cont();
            }).detach();
        }
 
        T await_resume() { return this->get(); }
    };
 
    return awaiter { std::move(future) };
}
 
// Utilize the infrastructure we have established.
std::future<int> compute(as_coroutine)
{
    int a = co_await std::async([] { return 6; });
    int b = co_await std::async([] { return 7; });
    co_return a * b;
}
 
std::future<void> fail(as_coroutine)
{
    throw std::runtime_error("bleah");
    co_return;
}
 
int main()
{
    std::cout << compute({}).get() << '\n';
 
    try
    {
        fail({}).get();
    }
    catch (const std::runtime_error& e)
    {
        std::cout << "error: " << e.what() << '\n';
    }
}

输出

42
error: bleah