我使用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);
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
如果我在boost :: any_cast代码中为reinterpret_cast更改static_cast,它似乎可行.但是我不确定这会带来什么后果.
你有什么想法?
有没有办法在不使用指针的情况下定义循环引用?
我需要有这样的事情:
struct A;
struct B {
A a;
};
struct A {
B b;
};
Run Code Online (Sandbox Code Playgroud)
谢谢!