Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-08-30 14:43:25


On Thursday 30 August 2001 02:48, you wrote:
> > optional<T> foo() {
> > if (everything_is_happy_in_the_world) {
> > return optional<T>(some_value);
> > }
> > else {
> > return optional<T>();
> > }
> > }
>
> Hmm. Good point again.
> Still, I think this shouldn't be the proper usage. I would write the above
> like this:
>
> optional<T> foo() {
>
> optional<T> result ;
>
> if (everything_is_happy_in_the_world) {
> *result =some_value;
> }
>
> return result ;
> }
>
> Supporting direct initialization has the drawback that both statements
> below become equivalent, which I find confusing:
>
> optional<int> v ;
>
> v = 3 ;
> *v = 4 ;

I personally don't mind this equivalence. It's the same thing one deals with
when using any or a variant type, except that instead of *v we have something
like any_cast<T>(v) or v.as<T>().

> unless the constructor is made explicit, but even then I find it confusing:
>
> optional<int> v ( 3 ) ;
> *v = 4 ;

This might be a good compromise. It looks strange when you name v (why would
it be optional if you have a value for it?), but it's not quite so
strange in a return statement.

> I might be happy with a third alternative, a named constructor:
>
> optional<int> v = optional<int>::create_initialized(3) ;
> *v = 4 ;

Yuck :)

> I still find odd to use it like you used it. I prefer no direct
> initialization.
> But if there is general agreement to support direct initialization I can
> add it (but only explicit or with a named constructor)

I don't have any actual experience with the optional type, so I'm just trying
to imagine how I would use it. Perhaps having direct initialization would be
confusing - you would know better than I for sure.

        Doug


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk