variant over base and derived classes

hello, How to determine the actual type of the object stored in a variant? struct S { virtual ~S() {} }; struct Deriv1 : public S { virtual ~Deriv1() {} }; struct Deriv2 : public S { virtual ~Deriv2() {} }; struct Deriv3 : public Deriv2 { virtual ~Deriv3() {} }; 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? How do I construct v polymorphically so that the real object is stored? regards,

AMDG On 12/8/2010 4:04 PM, Hicham Mouline wrote:
How to determine the actual type of the object stored in a variant?
struct S { virtual ~S() {} };
struct Deriv1 : public S { virtual ~Deriv1() {} };
struct Deriv2 : public S { virtual ~Deriv2() {} };
struct Deriv3 : public Deriv2 { virtual ~Deriv3() {} };
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?
You have to downcast before creating the variant. boost::variant only uses the static type of the object. In Christ, Steven Watanabe

On 12/08/10 18:14, Steven Watanabe wrote:
AMDG
On 12/8/2010 4:04 PM, Hicham Mouline wrote:
How to determine the actual type of the object stored in a variant?
struct S { virtual ~S() {} };
struct Deriv1 : public S { virtual ~Deriv1() {} };
struct Deriv2 : public S { virtual ~Deriv2() {} };
struct Deriv3 : public Deriv2 { virtual ~Deriv3() {} };
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?
You have to downcast before creating the variant. boost::variant only uses the static type of the object.
Why is downcasting needed instead of just eliminating the implicit upcasting to const S&. IOW, instead of: const S& s = d3; my_variant_t v = s; why not: my_variant_t v = d3; ? WARNING: not tested. -Larry
participants (3)
-
Hicham Mouline
-
Larry Evans
-
Steven Watanabe