GeezerVison is showing cpprefjp.github.io — std::optional::and_then - cpprefjp C++日本語リファレンス
最終更新日時:
2026年09月19日 21時31分51秒 (JST)
rotarymars
が更新
履歴
編集
function template
<optional>
std:: optional:: and_then (C++23)
// optional<T>版のオーバーロード
template < class F > constexpr auto and_then ( F && f ) & ; // (1) C++23
template < class F > constexpr auto and_then ( F && f ) && ; // (2) C++23
template < class F > constexpr auto and_then ( F && f ) const & ; // (3) C++23
template < class F > constexpr auto and_then ( F && f ) const && ; // (4) C++23
// optional<T&>版のオーバーロード (C++26)
template < class F > constexpr auto and_then ( F && f ) const ; // (5) C++26
概要
有効値を保持していれば、値に対してfを適用した結果をoptionalとして返す。
有効値を保持していなければ、std::nullopt を返す。
(1) : *thisが非const左辺値の場合
(2) : *thisが非const右辺値の場合
(3) : *thisがconst左辺値の場合
(4) : *thisがconst右辺値の場合
(5) : optional<T&>の場合
optional<T>では (1)~(4) が定義され、optional<T&>では (5) のみが定義される。
実際には複数オーバーロードが提供されるが、大まかには下記シグニチャのようにみなせる。
and_thenへは、引数リストに1個のT型をとりstd::optional<Return>型を返す関数や関数オブジェクトを与える。
適格要件
説明用のU型を次の通りとする:
remove_cvref_t <U>はoptionalの特殊化であること
効果
(1), (3) : 次と等価
(2), (4) : 次と等価
(5) : 次と等価
備考
and_thenは、メソッドチェーンをサポートするモナド風(monadic)操作として導入された。
関数型プログラミングの文脈における Monadic Bind 操作に対応する。
例
出力
バージョン
言語
処理系
関連項目
参照