名前空間
変種
操作

std::coroutine_traits

From cppreference.com
< cpp‎ | coroutine
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
コルーチンサポート
コルーチントレイト
coroutine_traits
(C++20)
コルーチンハンドル
No-opコルーチン
自明なawaitable
Rangeジェネレータ
(C++23)
 
ヘッダ <coroutine> で定義
template< class R, class... Args >
struct coroutine_traits;
(C++20以降)

コルーチンの戻り値の型とパラメーター型からプロミス型を決定します。標準ライブラリの実装は、修飾されたIDが有効で型を示す場合、R::promise_type と同じ公開アクセス可能なメンバー型 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
English 日本語 中文(简体) 中文(繁體)