Boost logo

Boost :

From: William E. Kempf (wekempf_at_[hidden])
Date: 2002-12-11 10:59:54


Fernando Cacciola said:
> From: "Joel de Guzman" <djowel_at_[hidden]>
>> From: "Fernando Cacciola" <fernando_cacciola_at_[hidden]>
>>
>> > > Hmmm, I'm not sure if I agree with this. T can very well be
>> > > uninitialized in the variant when nil_t is in effect. Then
>> > > nil_t can just be struct nil_t {}; which costs nothing to
>> initialize. Why is optional "more handy" in this regard?
>> > >
>> > Because it has an interface that makes it easier to deal with its
> possibly
>> > uninitialized state:
>> >
>> > optional<int> opt ;
>> > int x = *opt ; // Oops! opt is uninitialied. In debug this is an
> assertion
>> > failure, in release, a core-dump.
>> >
>> > *opt = 3 ; // initializes it.
>> >
>> > if ( int* x = get(opt) )
>> > some(*x)
>>
>> But of course you also have that interface with the variant.
>> Example:
>>
>> if (p = variant_cast<int>(pvar))
>> ...initialized
>> else
>> ...uninitialized
>>
>> or...
>>
>> int n = variant_cast<int>(var);
>> // Oops! var is uninitialied. throws bad_cast
>>
>> It's trivial to make that a free function like get. Or further, to
>> make a subset API for optional.
>>
> You can certainly do the same with variant. The point is that with
> optional<> it is *easier*.
> With optional<> you don't need to specify the type of the wrapped value
> all the time as with variant; and you don't need to explicitly test if
> the variant holds a "nil_t" in order to see if it is initialized.

To add my own 2 cents on why we should have optional<> instead of just
relying on variant<T, nil_t> is along the same lines as Fernando is trying
to convey here. A std::pair<int, int> provides all the functionality
you'd need for a "point" type in a GUI framework, but we'd still want to
have a point type (which may be implemented in terms of std::pair<int,
int>) in order to bring the syntax more in line with domain we're dealing
with. The exact same thing applies to optional and variant.

The argument about optimizing POD cases is less compelling. Even if the
optimization was considered necessary, I'd think you could provide it with
the variant<POD, nil_t> as well (though it would be a trickier
implementation).

William E. Kempf


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