boost :: variant和多态性

用户名

我想从boost变体中获取指向基类的指针,如果我将指针指向派生类。有什么办法可以做到这一点。以下代码不起作用。

class A{ public: virtual ~A(){}}; class B : public A{};
typedef boost::variant<A*,B*> MyVar;
MyVar var = new B;
A* a = boost::get<A*> (var); // the following line throws exception

也许有人知道如何编写我自己的get函数,该函数将测试所请求的类型是否为变量中存储类型的基类,然后执行适当的强制转换

用户名

嗨,谢谢大家的回答和评论。我来到以下内容,它们决定了编译时类型是否彼此继承。它似乎可行,而且对我来说似乎更容易理解。

 #include <iostream>
 #include <boost/variant.hpp>
 #include <boost/type_traits.hpp>
 #include <boost/utility.hpp>

 using namespace boost::type_traits;


 struct A { virtual ~A() {} virtual void foo() {} };
 struct B : A { virtual void foo() { std::cout << "B::foo()" << std::endl; } };

  typedef boost::variant<B*,A*,C*> MyVar;


template <typename A,typename B> 
struct types_are_inheritance_related
{ 
 static const bool value=     
 ice_or<
 boost::is_base_of<A, B>::value,
 boost::is_base_of<B, A>::value
 >::value;    
};


 template<class Base>
 class get_visitor
: public boost::static_visitor<Base*> { public:


template<class T>
Base* operator()( T* t, typename boost::enable_if<types_are_inheritance_related<Base,T> >::type* dummy = 0)
{
   Base* b = dynamic_cast<Base*> ( t);
   return b;           
}  

template<class T>
Base* operator()( T* t, typename boost::disable_if<types_are_inheritance_related<Base,T> >::type* dummy = 0)
{       
   return 0;        
}   
};

template<class T>
T* get_var_value(MyVar& var)
{
   get_visitor<T> visitor;
   T* aa= var.apply_visitor(visitor);
   return aa;
}

int main()
{    
 MyVar var = new B;

 A* a = get_var_value<A*>(var); // works!
 a->foo();

 B* b = get_var_value<B*>(var); // works!
 b->foo();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章