简体   繁体   English

如何使用boost :: any_cast(c ++库)转换为基类型?

[英]how to use boost::any_cast (c++ library) to cast to base types?

I am using boost::any to have polymorphic types, I need to be able to cast an object to its base type. 我使用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);
}

The code of the main function throws the following error at runtime: 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

If I change the static_cast in the boost::any_cast code for reinterpret_cast it seems to work. 如果我在boost :: any_cast代码中为reinterpret_cast更改static_cast,它似乎可行。 However I am not sure about the consequences of that. 但是我不确定这会带来什么后果。

Do you have any ideas? 你有什么想法?

Upcasts (towards pointer-to-base) don't require an explicit cast in C++. 向上(朝向指针)不需要在C ++中进行显式转换。

On the other hand, boost::any_cast will only succeed when casting to the exact same type as was originally stored. 另一方面, boost::any_cast只有在转换为与最初存储的完全相同的类型时才会成功。 (IIRC it uses typeid to check that you are trying to access the correct type, and typeid comparisons are only true for exact matches.) (IIRC使用typeid来检查您是否正在尝试访问正确的类型,而typeid比较仅适用于完全匹配。)

Hence: 因此:

A* aa = boost::any_cast<B*>(any);

However, it is somewhat unclear why you should be using boost::any for polymorphic types. 但是,有些人不清楚为什么你应该使用boost::any来实现多态类型。 In particular, it is not a smart pointer and will not delete the stored object. 特别是,它不是智能指针,不会删除存储的对象。 More common is to store pointers to polymorphic object in a smart pointer, eg boost::shared_ptr<A> 更常见的是在智能指针中存储指向多态对象的指针,例如boost::shared_ptr<A>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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