4
我正在使用boost :: any有多态类型,我需要能够将一个对象转换为它的基类型。如何使用boost :: any_cast(C++库)转换为基类型?
class A {
public:
int x;
virtual int foo()= 0;
};
class B : public A {
public:
int foo() {
return x + 1;
}
};
int main() {
B* bb = new B();
boost::any any = bb;
bb->x = 44;
A* aa = boost::any_cast<A*>(any);
}
主要功能的代码引发以下运行时错误:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >'
what(): boost::bad_any_cast: failed conversion using boost::any_cast
Abort trap
如果我改变的static_cast在升压::对的reinterpret_cast似乎工作any_cast代码。但我不确定这会带来什么后果。
你有什么想法吗?
按值存储任何对象并删除它 – Sergei 2017-09-10 10:07:05