std::optional::value_or() – lazy argument evaluation

  • A+

Is it possible to evaluate std::optional::value_or(expr) argument in a lazy way, so the expr were calculated only in the case of having no value? If not, what would be a proper replacement?


You may write your helper function:

template<typename T, typename F> T lazy_value_or(const std::optional<T> &opt, F fn) {     if(opt) return opt.value();     return fn(); } 

You can then use this as:

lazy_value_or(v, [] { return expensive_computation();}); 

If that's significatively less typing than doing it explicitly that's up to you to judge; OTOH, you can ease this up with some macros:

#define LAZY_VALUE_OR(opt, expr) /     lazy_value_or((opt), [&] { return (expr);}) 

To be used as

LAZY_VALUE_OR(opt, expensive_calculation()) 

this is closest to what I think you want, but may be frowned upon as it hides a bit too much stuff.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: