6

我正在使用 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);
}

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

如果我将 boost::any_cast 代码中的 static_cast 更改为 reinterpret_cast 它似乎可以工作。但是我不确定这样做的后果。

你有什么想法?

4

1 回答 1

11

向上转换(指向指向基址的指针)不需要在 C++ 中进行显式转换。

另一方面,boost::any_cast只有在转换为与最初存储的完全相同的类型时才会成功。(IIRC 它使用 typeid 来检查您是否尝试访问正确的类型,并且 typeid 比较仅适用于完全匹配。)

因此:

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

但是,有些不清楚为什么应该使用boost::any多态类型。特别是,它不是智能指针,不会删除指向的对象。更常见的是将指向多态对象的指针存储在智能指针中,例如boost::shared_ptr<A>

于 2009-10-27T15:45:51.280 回答