4

boost::any用来存储指针,想知道是否有办法提取多态数据类型。

这是理想情况下我想做的一个简单示例,但目前不起作用。

struct A {};

struct B : A {};

int main() {

    boost::any a;
    a = new B();
    boost::any_cast< A* >(a);
}

这失败了,因为 a 正在存储 B*,而我正在尝试提取 A*。有没有办法做到这一点?

谢谢。

4

3 回答 3

7

Boost.DynamicAny 是 Boost.Any 的变体,它提供了更灵活的底层类型的动态转换。虽然从 Boost.Any 检索值要求您知道存储在 Any 中的确切类型,但 Boost.DynamicAny 允许您动态转换为所持有类型的基类或派生类。

https://github.com/bytemaster/Boost.DynamicAny

于 2011-03-04T04:50:03.893 回答
4

另一种方法是将 an 存储A*在 the 中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;
}
于 2009-07-06T20:11:30.403 回答
3

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

static_cast<A*>(boost::any_cast<B*>(a))
于 2009-07-06T19:04:52.223 回答