Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain Optionals in C++

How to avoid nested if statements with chained optionals in C++?

For example, if type A contains an std::optional<B> b and type B an std::optional<C> c, I would like to be able to write something like:

const auto v = if_exists(if_exists(a->b)->c);

And v would get the value from c or an empty optional if either b or c are empty optionals.

I think this would be nicer that nested ifs like this:

if (a->b) {
 const auto b = *(a->b);
 if (b->c) {
  const auto c = *(b->c);
 }
}

The following question seems to go in this direction but I am not sure how to adapt it to my use-case: Haskell style "Maybe" type & *chaining* in C++11

like image 605
Wilhem Meignan Avatar asked Feb 21 '18 12:02

Wilhem Meignan


1 Answers

This can be achieved with a simple macro.

#define CHAIN(OPTIONAL, MEMBER)                                                 \
  ([](auto &&opt) {                                                             \
    return opt ? std::optional{opt->MEMBER} : std::nullopt;                     \
  }(OPTIONAL))

const auto v = CHAIN(CHAIN(a, b), c);
like image 83
Indiana Kernick Avatar answered Oct 10 '22 23:10

Indiana Kernick