|
Boost : |
Subject: Re: [boost] [optional] Safe optional
From: Matt Calabrese (rivorus_at_[hidden])
Date: 2014-11-17 11:41:47
On Nov 17, 2014 1:25 AM, "Andrzej Krzemienski" <akrzemi1_at_[hidden]> wrote:
> No, no exceptions.
> The solution is based on the observation that there is a limited number of
> things you can do with optional<T>
>
> optional<int> oi = ...;
>
> 1:
> if (oi) doSomething(*oi);
> else doSomethingElse(); // or nothing
>
> 2:
> if (oi) doSomething(*oi);
> else doSomething(-1); // use default value
>
> 3:
> if (!oi) oi = (int)getIntByOtherMeans();
> doSomething(*oi); // now it is safe
>
> Now we simply provide a dedicated interface for each of these three
usages:
>
> 1:
> oi.use(&doSomething, &doSomethingElse); // or use lambdas
>
> 2:
> doSomething(oi.value_or(-1));
>
> 3:
> doSomething(oi.value_or_eval(getIntByOtherMeans));
While I agree that we should be encouraging high order functions/visitation
here, my personal experience is simply that many people do not like it.
When given the choice to pass a lamda or to use an "if" or a
range-based-for over high order function alternatives, programmers will
generally opt for not using a lambda. The fact that Bjarne thinks
visitation is somehow "bad" doesn't help. I agree that it's safer and I'd
be in favor of it, but be aware that not everyone will like it.
That said, I'd be in favor of this. If going with this approach, though,
I'd say make optional a model of a variant and/or discriminated union
concept that it and variant share, along with "expected" if it were to make
it into boost (I.E. allow for apply_visitor of T and none, provide a
"which"). I'd still like to see the other functions you mention as well for
convenience.
I know that there are others (Eric?) who prefer to think of optional as a
container of size 0 or 1, so it could also make sense to provide an
accessor to a range. One interesting effect of this is that now
range-based-for sort of becomes a "visit if." There are probably other...
interesting uses of standard algorithms.
> I would rather not go that way. boost::optional is not unsafe. It is
simply
> something else than what some people think. Its conceptual model is more
> like any value of T, plus one additional value. In this model implicit
> conversions make perfect sense and are n fact desirable.
I'm not sure I agree. These two templates aren't exactly complimentary in
terms of the functionality that they provide, they really would just
provide exactly the same functionality with the same internals. All that is
different is the interface. Because of that, I say either it replaces
optional or it doesn't exit as a part of boost. If people are convinced
that this interface is less error prone, then it should be THE interface
for optional.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk