名稱空間
變體
操作

std::coroutine_traits

來自 cppreference.com
< cpp‎ | 協程
 
 
 
協程支援
協程特質
coroutine_traits
(C++20)
協程控制代碼
無操作協程
平凡可等待物件
範圍生成器 (Range generators)
(C++23)
 
定義於標頭檔案 <coroutine>
template< class R, class... Args >
struct coroutine_traits;
(C++20 起)

根據協程的返回型別和引數型別確定其 Promise 型別。如果 qualified-id 有效並表示一個型別,標準庫實現提供一個公共可訪問的成員型別 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