【问题标题】:how to use boost::any_cast to cast to base types?如何使用 boost::any_cast 转换为基本类型?
【发布时间】:2009-10-27 10:33:18
【问题描述】:

我正在使用 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,它似乎可以工作。但是我不确定这样做的后果。

你有什么想法吗?

【问题讨论】:

    标签: c++ boost casting boost-any


    【解决方案1】:

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

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

    因此:

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

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

    【讨论】:

    • @Serg:是的,但是删除指针并不会删除指向的对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多