c++ - 如何使用 boost::any_cast 转换为基本类型?

标签 c++ boost casting boost-any

我正在使用 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::any_cast只有在转换为与最初存储的类型完全相同的类型时才会成功。 (IIRC 它使用 typeid 来检查您是否正在尝试访问正确的类型,并且 typeid 比较仅适用于完全匹配。)

因此:

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

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

关于c++ - 如何使用 boost::any_cast 转换为基本类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1629938/

相关文章:

c++ - operator= 从模板类重载

c++ - 使用 QtSDK 中的 mingw 构建 boost

c++ - 在 IAR 的 C++ 编译器中使用 Boost

c++ - C++11 中的 BOOST scoped_lock 替换

optimization - 为什么即使在本例中已经确定了类型,但仍然需要强制转换类型?

C++ 继承和成员访问问题

c++ - 根据需要 QTableView dosent View 值的模型

c++ - 即使我在 .cpp 文件中实例化虚拟对象,.cpp 文件内的模板函数定义也不起作用

c++ - NRVO 案例中 const 返回类型的相关性

c++ - boost::thread join 函数 block 调用线程