C++ 具有boost::shared_ptr的多态强制转换
我熟悉boost在普通指针上的C++ 具有boost::shared_ptr的多态强制转换,c++,boost,polymorphism,smart-pointers,C++,Boost,Polymorphism,Smart Pointers,我熟悉boost在普通指针上的polymorphic_cast: Base *base; Derived *d = boost::polymorphic_cast<Derived>(base); 使用 Posi::StasyPoType投< >代码> Boo::DycRyPoPoTythICAST < /C> >,作为C++的类似代码:代码> STATICECAST 和 DyrimaCase: boost::shared_ptr<Derived> d = boost
polymorphic_cast
:
Base *base;
Derived *d = boost::polymorphic_cast<Derived>(base);
使用<代码> Posi::StasyPoType投< <代码> >代码> Boo::DycRyPoPoTythICAST < /C> >,作为C++的类似代码:代码> STATICECAST 和<代码> DyrimaCase:
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(base);
// now "d" shares ownership with "base"
boost::shared\u ptr d=boost::static\u pointer\u cast(基本);
//现在“d”与“base”共享所有权
这只是对底层原始指针执行相应的强制转换
(C++11标准库中的
std
命名空间和C++03的tr1库中的std::tr1
名称空间也是如此。)谢谢。没有boost::多态指针\u cast
?我想只需要使用dynamic并显式地编写assert…@Roddy:据我所知,这是不可能的。但是如果需要检查是否成功,您可以总是说类似于if(auto p=boost::dynamic_pointer_cast(base)){/*…*/}
,反之如何?我希望公共代码使用shared_ptr,并从派生了shared_ptr的派生类调用它…@deniseskimore:相反的转换已经隐式启用。boost::多态性_指针_cast/downcast(您正在寻找向下转换)已在(我相信从1.58.0开始)
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(base);
// now "d" shares ownership with "base"