Boost logo

Boost Users :

Subject: Re: [Boost-users] variant over base and derived classes
From: Diederick C. Niehorster (dcnieho_at_[hidden])
Date: 2010-12-09 08:50:19


(sorry if this is a top post, my phone shows no msg quotes)

I'm no expert on this, but isn't there an compile time function to
testing if an instance is derived from another (in introspection or
something)? You could then maybe sort the variant types for most to
least derived and then test untill you find the suitable cast?

Just brainstorming pretty much. Hope its useful!

Best,
Dee

On 09/12/2010, Hicham Mouline <hicham_at_[hidden]> wrote:
>>> -----Original Message-----
>>> From: Hicham Mouline [mailto:hicham_at_[hidden]]
>>> Sent: 09 December 2010 00:04
>>> To: 'boost-users_at_[hidden]'
>>> Subject: variant over base and derived classes
>>>
>>> hello,
>>> <snip>
>>>
>>> typedef boost::variant<S,Deriv1, Deriv2, Deriv3> my_variant_t;
>>>
>>> Deriv3 d3;
>>>
>>> struct print_type: public boost::static_visitor<> {
>>> template <typename T>
>>> void operator()(const T&) const
>>> {
>>> std::cout<< typeid(T).name() <<std::endl;
>>> }
>>> };
>>>
>>> const S& s = d3;
>>> my_variant_t v = s;
>>> boost::apply_visitor( print_type(), v );
>>>
>>> This prints S.
>>>
>>> Is it a truncated copy of d3 that is stored v?
>>Yes.
>>> How do I construct v polymorphically so that the real object is stored?
>>>
>>> regards,
>>You have to downcast before creating the variant.
>>boost::variant only uses the static type of the object.
>>In Christ,
>>Steven Watanabe
>
> If I am given a const S* sptr, how do I construct an instance of the above
> variant then?
>
> const Deriv1* d1ptr; const Deriv2* d2ptr; const Deriv3* d3ptr;
> my_variant_t v = ((d1ptr = dynamic_cast<const Deriv1*>(sptr)) != 0 )?
> *d1ptr:
> ((d2ptr = dynamic_cast<const Deriv2*>(sptr)) != 0 )? *d2ptr:
> ((d3ptr = dynamic_cast<const Deriv3*>(sptr)) != 0 )? *d3ptr: *sptr;
>
> Is there a better way of writing this?
>
> rds,
>
> --------------------------------------------
>
> Trying to do this more generically, I've thought of call mpl::for_each on
> the ::types of the variant to see which dynamic_cast works.
> The problem is that I need the most derived type to be stored in the
> variant.
> I can see how to do it by a virtual function but that is completely
> intrusive.
>
> regards,
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net