Boost::any 和多态性
我正在使用 boost::any
来存储指针,并且想知道是否有 一种提取多态数据类型的方法。
这是一个简单的例子,说明了理想情况下我想做的事情,但目前不起作用。
struct A {};
struct B : A {};
int main() {
boost::any a;
a = new B();
boost::any_cast< A* >(a);
}
这失败了,因为 a 正在存储 B*,而我正在尝试提取 A*。 有办法做到这一点吗?
谢谢。
I am using boost::any
to store pointers and was wondering if there was
a way to extract a polymorphic data type.
Here is a simple example of what ideally I'd like to do, but currently doesn't work.
struct A {};
struct B : A {};
int main() {
boost::any a;
a = new B();
boost::any_cast< A* >(a);
}
This fails because a is storing a B*, and I'm trying to extract an A*. Is there a way to accomplish this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Boost.DynamicAny 是 Boost.Any 的变种,它提供了更灵活的底层类型动态转换。 从 Boost.Any 检索值需要您知道 Any 中存储的确切类型,而 Boost.DynamicAny 允许您动态转换为所保存类型的基类或派生类。
https://github.com/bytemaster/Boost.DynamicAny
Boost.DynamicAny is a vairant on Boost.Any which provides more flexible dynamic casting of the underlying type. Whereas retreiving a value from Boost.Any requires that you know the exact type stored within the Any, Boost.DynamicAny allows you to dynamically cast to either a base or derived class of the held type.
https://github.com/bytemaster/Boost.DynamicAny
另一种方法是将
A*
存储在boost::any
中,然后将dynamic_cast
输出。 就像是:The other way is to store an
A*
in theboost::any
and thendynamic_cast
the output. Something like:不幸的是,我认为唯一的方法是:
Unfortunately, I think the only way to do it is this: