Boost::any 和多态性

发布于 2024-07-26 01:25:00 字数 326 浏览 6 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

め可乐爱微笑 2024-08-02 01:25:00

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

浪漫人生路 2024-08-02 01:25:00

另一种方法是将 A* 存储在 boost::any 中,然后将 dynamic_cast 输出。 就像是:

int main() {
    boost::any a = (A*)new A;
    boost::any b = (A*)new B;
    A *anObj = boost::any_cast<A*>(a);
    B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL

    anObj = boost::any_cast<A*>(b);
    anotherObj = dynamic_cast<B*>(anObj); // <- this one works!

    return 0;
}

The other way is to store an A* in the boost::any and then dynamic_cast the output. Something like:

int main() {
    boost::any a = (A*)new A;
    boost::any b = (A*)new B;
    A *anObj = boost::any_cast<A*>(a);
    B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL

    anObj = boost::any_cast<A*>(b);
    anotherObj = dynamic_cast<B*>(anObj); // <- this one works!

    return 0;
}
甜是你 2024-08-02 01:25:00

不幸的是,我认为唯一的方法是:

static_cast<A*>(boost::any_cast<B*>(a))

Unfortunately, I think the only way to do it is this:

static_cast<A*>(boost::any_cast<B*>(a))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文