简体   繁体   中英

Boost::any and polymorphism

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.

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

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;
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM