小编Mic*_*hel的帖子

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

我使用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);
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

如果我在boost :: any_cast代码中为reinterpret_cast更改static_cast,它似乎可行.但是我不确定这会带来什么后果.

你有什么想法?

c++ casting boost-any

6
推荐指数
1
解决办法
1万
查看次数

C++中的循环引用,没有指针

有没有办法在不使用指针的情况下定义循环引用?

我需要有这样的事情:

struct A;
struct B {
    A a;
};

struct A {
    B b;
};
Run Code Online (Sandbox Code Playgroud)

谢谢!

c++ pointers circular-reference

5
推荐指数
3
解决办法
6392
查看次数

标签 统计

c++ ×2

boost-any ×1

casting ×1

circular-reference ×1

pointers ×1