最終更新日時(UTC):
が更新

履歴 編集

function template
<expected>

std::expected.void::and_then(C++23)

// expected<cv void, E>部分特殊化
template<class F> constexpr auto and_then(F&& f) &;        // (1)
template<class F> constexpr auto and_then(F&& f) const &;  // (2)
template<class F> constexpr auto and_then(F&& f) &&;       // (3)
template<class F> constexpr auto and_then(F&& f) const &&; // (4)

概要

正常値を保持していれば、fの呼び出し結果をexpectedとして返す。 エラー値を保持していれば、そのまま返す。

実際には複数オーバーロードが提供されるが、大まかには下記シグニチャのようにみなせる。 and_thenへは、引数をとらずstd::expected<Return, E>型を返す関数や関数オブジェクトを与える。

template <cv void, class E>
class expected {
  template <class Return>
  std::expected<Return, E> and_then(function<std::expected<Return, E>()> func);
};

テンプレートパラメータ制約

適格要件

効果

備考

and_thenは、メソッドチェーンをサポートするモナド風(monadic)操作として導入された。

#include <cassert>
#include <expected>
#include <string>

std::expected<void, std::string> ok()
{
  return {};
}

std::expected<void, std::string> ng()
{
  return std::unexpected{"ng"};
}

int main()
{
  std::expected<void, std::string> v1;
  assert(v1.and_then(ok).has_value());

  std::expected<void, std::string> v2;
  assert(v2.and_then(ng).error() == "ng");

  std::expected<void, std::string> e1 = std::unexpected{"empty"};
  assert(e1.and_then(ng).error() == "empty");
}

出力

バージョン

言語

  • C++23

処理系

関連項目

参照