|
Boost : |
From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-08-20 14:25:40
On Saturday 18 August 2001 08:06, you wrote:
[snip VLAs]
> > > > * a variant type, both unconstrained (any, or variant<void>) and
> >
> > constrained
> >
> > > > (variant<T>).
> > >
> > > Waste of time. I built one of these, and it is too hard to
> > > use to bother.
> >
> > My experience is somewhat different.
> >
> > class xml_element;
> > class xml_text: public xml_element;
> > class xml_tag: public xml_element;
>
> This is not a proper variant construction, unfortunately.
> It is a common abuse of inheritance to try to emulate the missing
> functionality. To make it work, you have to use RTTI, and the result
> isn't safe: you can try to make it safer by providing some
> 'convenience' functionality, but you can't force people
> to use it. :-(
>
> Compare with SML:
>
> type t = X of int | Y of float
> match e with
>
> | X x -> print_int x
> | Y y -> print_float y
>
> where type safety is enforced, and, in most cases,
> completeness of decoding checked.
>
> My point is: you gain very little with any
> emulation of variants in C++, over the C technique
> of casting a void *. That's also precisely how I
> implement variants in the code generated by Felix.
> [Of course, I know the casts are safe]
>
> If we're going to enshrine variants in C++,
> they should be done properly: by an extension
> to the core language.
[snip 'adding features to core' discussion]
I might as well feed the flames a bit... I'm not sure I agree that there is
any reason to add variants into the core C++ language. With a little bit of
work I was able to come up with syntax similar to the above.
variant<int, double, std::string, etc> v;
variant_switch(v)
.on<std::string>(print_string())
.on<int>(print_int())
.on_default(print_unknown());
These variants are efficient and typesafe. Am I missing some key feature that
would require language support? (Note: the max number of allowed types in a
variant will be dependent on a macro as soon as the PREPROCESSOR library is
available, so that doesn't count).
Doug
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk