TartanLlama / optional

C++11/14/17 std::optional with functional-style extensions and reference support
https://tl.tartanllama.xyz
Creative Commons Zero v1.0 Universal
859 stars 67 forks source link

Add a trivial `apply` function #59

Open smitsyn opened 1 year ago

smitsyn commented 1 year ago

Imagine a scenario where a several transformations have to be applied to an optional:

optional<Tb> func_a(Ta);
optional<Tc> func_b(optional<Tb>);
optional<Td> func_c(Tc);

optional<Ta> opt;

Currently this is done in this way, where orders in which functions are written and applied is inconsistent:

func_b(opt.and_then(func_a)).and_then(func_c);

I propose adding a trivial member function apply(F f) to optional that applies f to *this, so the code above can be written as:

opt.and_then(func_a).apply(func_b).and_then(func_c);

In this example, function names are written down in the order they are called, so it looks much cleaner. Probably if we could have UFCS, this wouldn't be needed.

In real world these functions could be lambdas written in-line and consisting of several lines, so this order inconsistency may look really ugly.