我正在使用 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,它似乎可以工作。但是我不确定这样做的后果。
你有什么想法吗?
最佳答案
向上转换(指向指向基的指针)不需要在 C++ 中进行显式转换。
另一方面,boost::any_cast
只有在转换为与最初存储的类型完全相同的类型时才会成功。 (IIRC 它使用 typeid 来检查您是否正在尝试访问正确的类型,并且 typeid 比较仅适用于完全匹配。)
因此:
A* aa = boost::any_cast<B*>(any);
但是,您不太清楚为什么要使用 boost::any
对于多态类型。特别是,它不是智能指针,不会删除指向的对象。更常见的是将指向多态对象的指针存储在智能指针中,例如 boost::shared_ptr<A>
关于c++ - 如何使用 boost::any_cast 转换为基本类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1629938/