Boost logo

Boost :

From: Oleg Grunin (ogrunin_at_[hidden])
Date: 2003-11-08 02:37:15

It's kind of sad that boost::variant lacks implicit conversion to each
of its bound types. 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;

along with:

int i = get<int>(v1);

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.
One solution could be to have variant inherit from a series of helper
conversion classes parametrized with each of its bound types.

Something along these lines:

template <class Derived, class T>
struct Converter {
        operator T& () {
                return get<T>(static_cast<Derived&>(*this));

template <class T1, T2, T3 /*, ... */>
class variant : public mpl::inherit_linearly<
                mpl::list<T1, T2, T3 /*, ... */ >
                                variant<T1, T2, T3 /*, ... */>

Now one can say:

int i = v1;
double d = v1;
char c = v1;

but not

char *s = v1;

and the error message actualy makes sense: can't convert V1 to char *.

Boost list run by bdawes at, gregod at, cpdaniel at, john at