Boost logo

Boost :

Subject: Re: [boost] An extension to boost::variant
From: Chris Hamilton (chamilton_at_[hidden])
Date: 2009-02-09 14:53:45


>> boost::variant
>> currently can not handle the following code:
>> [...]
>> boost::variant<foo*,foo&> v;
>> [...]
>> My question is essentially this: why couldn't it?
>
> I suppose it requires the types to be value types, otherwise assignment
> and copy don't make sense.
> It's just like containers really. What's wrong with using T* or
> reference_wrapper<T> instead of T&?

reference_wrapper *almost* does what I want it to, but it requires
conscious effort on behalf of the user. For example, the following
compiles and runs:

struct foo {};

int main(int argc, const char** argv)
{
    foo f;
    foo* pf = &f;

    boost::variant<foo*,boost::reference_wrapper<foo> > v;

    v = boost::reference_wrapper<foo>(f);
    printf("%d\n", & (boost::get<boost::reference_wrapper<foo>
>(v).get() ) == &f);

    v = pf;
    printf("%d\n", boost::get<foo*>(v) == pf);

    pf = NULL;
    printf("%d\n", boost::get<foo*>(v) != pf)

    return 0;
}

The problem is that the user has to be aware that they are passing a
reference by explicitly wrapping it. The problem is that boost::variant
doesn't know how to handle an '= instance_of_foo', and realize this
means it should be using the boost::reference_wrapper<foo> type.

Cheers,

Chris


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