C++23的可选::transform和可选::and_then有什么区别?

ein*_*ica 14 c++ monads monad-transformers stdoptional c++23

C++23 添加了一些关于可选值的“monadic-style”功能,作为以下方法optional<T>

optional<T>::and_then()(并忽略 的限定符this):

template<class F> constexpr auto and_then(F&& f); 
Run Code Online (Sandbox Code Playgroud)

返回对包含的值(如果存在)调用 f 的结果。否则,返回返回类型的空值。

optional<T>::transform()(并忽略 的限定符this):

template<class F> constexpr auto transform(F&& f);
Run Code Online (Sandbox Code Playgroud)

如果包含一个值,则返回一个包含对所包含值std::optional调用的结果的。否则,返回此类类型的空值。f*thisstd::optional

那么,这两个函数不是在做同样的事情吗?

ein*_*ica 22

假设你有一个optional<T1>值。

  • transform()让您可以将选项传递给诸如T2 foo(T1 x);之类的函数
  • and_then()让您可以将选项传递给诸如optional<T2> bar(T1 x);之类的函数

optional<T2>...最后得到一个。因此,transform()将函数的输出“重新装箱”为可选值,同时and_then()期望函数自行返回装箱值。

您可能还会想到transformstd::transform您将一个函数应用于“每个元素”;在容器中,它可以是任意数量的元素,在可选元素中,它可以是 0 或 1 个元素。

另请参阅这个问题

  • @einpoklum 单子操作的要点是将对象保留为“可选”,并且仅在完成所有操作后才将其解开。“and_then”需要为“可选”编写的函数,其中“transform”使非“可选”函数在“可选”上下文中可用。 (6认同)