我正在使用 boost::any 来拥有多态类型,我需要能够将对象转换为其基本类型。
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);
}
main函数的代码在运行时抛出如下错误:
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
如果我将 boost::any_cast 代码中的 static_cast 更改为 reinterpret_cast 它似乎可以工作。但是我不确定这样做的后果。
你有什么想法?