
On Sunday 12 March 2006 11:38, Václav Veselý wrote:
There is a common need of getting a value from an optional with possibility to define a default value in case of the optional is uninitialized. I suggest two alternatives:
optional<int> o; int i = o.get(123); // a meber function get with an additional parameter int j = from_optional(o, 123); // a free function
Both alternatives can be implemented simultaneously.
What do you think about it?
I don't like the first one, it's just not intuitive enough. With the second one, same problem though maybe that's just the name. Also, if there is a sensible default, there is no need for optional<> anyways. Also, they don't provide much advantage to the ternary operator int i = o ? *o : 123; just that you only have one 'o' in there instead of two. However, I just had a crazy idea, how about overloading an operator for them: int i = o | 123; int j = o / 456; int k = *(o|123); or maybe putting this choice into the name like int l = o.get_value_or(012); Biggest problem with the operator approach is that it might obfuscate things in that it is not immediately clear whether the state of the optional or the value of the optional is used. Also, I can see many optionals being used in boolean operations (e.g. with ||) so it might be a bad idea overloading operator|, too.... Just curious, does anybody know of a lib that uses operator- for string concatenation? Uli