如何使用 boost::any_cast 转换为基本类型?
我使用 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,它似乎可以工作。但我不确定这样做的后果。
你有什么想法吗?
I am using boost::any to have polymorphic types, I need to be able to cast an object to its base type.
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);
}
The code of the main function throws the following error at runtime:
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
If I change the static_cast in the boost::any_cast code for reinterpret_cast it seems to work. However I am not sure about the consequences of that.
Do you have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向上转换(朝向基点指针)不需要在 C++ 中进行显式转换。
另一方面,boost::any_cast 仅当转换为与最初存储的类型完全相同时才会成功。 (IIRC 它使用 typeid 来检查您是否正在尝试访问正确的类型,并且 typeid 比较仅适用于完全匹配。)
因此:
但是,有些不清楚为什么您应该使用
boost::any 用于多态类型。特别是,它不是智能指针,不会删除所指向的对象。更常见的是在智能指针中存储指向多态对象的指针,例如boost::shared_ptr
Upcasts (towards pointer-to-base) don't require an explicit cast in C++.
On the other hand,
boost::any_cast
will only succeed when casting to the exact same type as was originally stored. (IIRC it uses typeid to check that you are trying to access the correct type, and typeid comparisons are only true for exact matches.)Hence:
However, it is somewhat unclear why you should be using
boost::any
for polymorphic types. In particular, it is not a smart pointer and will not delete the pointed-at object. More common is to store pointers to polymorphic object in a smart pointer, e.gboost::shared_ptr<A>