我熟悉 boost 在普通指针上的 polymorphic_cast
:
Base *base;
Derived *d = boost::polymorphic_cast<Derived>(base);
但是,如何将它与 boost::shared_ptr
一起使用呢?
boost::shared_ptr<Base> base;
boost::shared_ptr<Derived> d = boost::?????(base);
最佳答案
使用 boost::static_pointer_cast
或 boost::dynamic_pointer_cast
,作为 C++ 类型转换 static_cast
和 dynamic_cast
的类比>:
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(base);
// now "d" shares ownership with "base"
这只是对底层原始指针执行相应的转换。
(同样适用于 C++11 标准库中的 std
命名空间和 C++ TR1 库中的 std::tr1
命名空间03.)
关于c++ - 使用 boost::shared_ptr 进行多态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490190/