Boost logo

Boost :

From: Eric Friedman (ebf_at_[hidden])
Date: 2003-11-08 03:44:55


Oleg Grunin wrote:

> It's kind of sad that boost::variant lacks implicit conversion to each
> of its bound types.

This is by design. Evidence of it being good design is the similarity to
need for dynamic_cast when casting polymorphic types. That is,

   variant< int, std::string > v = ...;
   std::string& s = get<std::string>( v );

is the analogue of the following:

   base& b = ...;
   derived& d = dynamic_cast<derived&>( b );

Just as C++ does not allow you to cast from a superclass to subclass
without explicit casting, Boost.Variant does not allow you to "cast"
from a union of types (i.e., a variant) to a specific type.

> I think, convience and symmetry calls for the syntax like this:
>
> typedef variant<int, double, char> V1;
>
> V1 v1(1);
> v1 = 2;
> int i = v1;

I disagree. Information is lost with assignment to a variant; the reason
for the visitation mechanism is to cope with this fact.

> I realize that adding:
>
> template <class T>
> operator T& ();
>
> and throwing an exception if the types don't match is not very appealing
> as it would open it up to all kinds of misuse.
>
> It is, probably, possible, though, to devise a scheme where variant
> provides conversions only to the types it actually holds.
[snip]

While your proposal is certainly technically feasible, it doesn't
actually prevent accidental misuse. Instead it only *limits* the
potential for such misuse, which IMO is not good enough for a component
as general purpose as variant.

Sorry,
Eric


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