0

std::optional has the method

template< class U > constexpr T value_or( U&& default_value ) const&;

and yet, it doesn't have the constructor

template< class U > optional(bool condition, const U& value );

which seeps like the opposite thing. Alternatively, you would expect it to have the static method / named constructor idiom:

constexpr std::optional<T> value_if(bool condition, const T& value) {
    return condition ? nullopt : std::optional(value);
}

My questions:

  1. Is there a conceptual problem with a value_if (in either of the variants I listed)?
  2. Was something like that proposed to go into the standard?

Note: I wasn't sure whether to have const T& value or const T&& value.

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

2

Is there a conceptual problem with a value_if (in either of the variants I listed)?

Yes. It requires that you create a live T object, even if your condition is creating a nullopt. Whereas doing auto t = cond ? optional<T>(expr) : nullopt; inline will only evaluate expr if cond is true.

For example:

auto optStr1 = value_if(cond, get_object(...)); //Will *always* evaluate get_object
auto optStr2 = cond ? optional(get_object(...)) : nullopt; //Will only evaluate get_object if `cond` is true

Was something like that proposed to go into the standard?

No.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • I'm not sure I understand. At which point will a live T object be created, if I pass by reference? I mean, there's the initial argument I pass to `value_if`, which is an existing object I pass a reference to; and there's the construction in the third clause of the trinary operator - but it's short-circuilt logic, so that doesn't actually get called. Or am I missing something? – einpoklum Oct 17 '16 at 12:54
  • @einpoklum: See the added examples. – Nicol Bolas Oct 17 '16 at 12:59
  • Ah, but that's exactly the same as `my_optional.value_or(get_object(...))` , which could be replaced with `auto v = my_optional ? my_optional.value : v{}`; – einpoklum Oct 17 '16 at 13:17
  • @einpoklum: I don't think there's any reason for one over the other, except for user expectations. `value_or` is a nice convenience function that many users expect. A constructor to compliment that apparently isn't that expected. – GManNickG Oct 18 '16 at 00:27