Boost logo

Boost :

From: Vaclav Vesely (vaclav.vesely_at_[hidden])
Date: 2006-03-12 16:49:31

Ulrich Eckhardt wrote:
> 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
> I don't like the first one, it's just not intuitive enough.

Maybe better selected name could be more intuitive.

> Also, if there is a
> sensible default, there is no need for optional<> anyways.

I don't think so. Library functions can return optionals and it depends
on the user of library if there is a default value and what is is.

> 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.

There are two points:
1) As Sebastian Redl in another post said, o can be returned from function.
2) I think, that my proposal is more readable and elegant.

> 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);

I don't like this much. I prefer descriptive function names to weirdly
overloaded operators.

> or maybe putting this choice into the name like
> int l = o.get_value_or(012);

I would be satisfied with any reasonable name.

Except of replacing missing value with default there is are more
strategies of handling missing values. For example Property Tree library
(which is scheduled for review) has four (!) methods for getting value
with for ways of handle the case of missing value. That strategies are
throwing an exception, return default value, return optional and get the
value in an out parameter and returning only the flag. I think, that all
these strategies should be solved in optional library. The method names
could be:

        val = opt.get_or_exception()
        val = opt.get_or_default(123)
        tie(flag, val) = opt.get_tuple()
        flag = opt.get_xxx(val) // reference to a variable

I'm not sure with the neme of the last version.


Boost list run by bdawes at, gregod at, cpdaniel at, john at