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

履歴 編集

function template
<expected>

std::expected::transform(C++23)

template<class F> constexpr auto transform(F&& f) &;        // (1)
template<class F> constexpr auto transform(F&& f) const &;  // (2)
template<class F> constexpr auto transform(F&& f) &&;       // (3)
template<class F> constexpr auto transform(F&& f) const &&; // (4)

概要

正常値を保持していれば、正常値に対してfを適用した結果をexpectedの正常値として格納して返す。 エラー値を保持していれば、そのまま返す。

実際には複数オーバーロードが提供されるが、大まかには下記シグニチャのようにみなせる。 transformへは、引数リストに1個のT型をとりReturn型を返す関数や関数オブジェクトを与える。

template <class T, class E>
class expected {
  template <class Return>
  std::expected<Return, E> transform(function<Return(T)> func);
};

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

適格要件

効果

備考

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

#include <cassert>
#include <expected>
#include <numeric>
#include <string>
#include <vector>

// 1..N数列を生成する関数
std::vector<int> make_seq(int n)
{
  std::vector<int> seq(n, 0);
  std::iota(seq.begin(), seq.end(), 1);
  return seq;
}

int main()
{
  std::expected<int, std::string> v1 = 3;
  assert((v1.transform(make_seq).value() == std::vector<int>{1,2,3}));

  std::expected<int, std::string> e1 = std::unexpected{"NaN"};
  assert(e1.transform(make_seq).error() == "NaN");
}

出力

バージョン

言語

  • C++23

処理系

関連項目

参照