shared_ptr的隐式转换

Ste*_*ve 4 c++ shared-ptr

我有两个类U和T的shared_ptrs,其中T是U的基础.

这是没有问题的,从做一个隐式转换shared_ptr<U>shared_ptr<T>.但也有可能做到转换shared_ptr<T>shared_ptr<U>

我尝试了这种消化的解决方案:

class T {
public:
  virtual ~T() {}
protected: 
  void fillData() = 0;
};

class Timpl : public T 
{ 
public:
  virtual ~Timpl() {}
protected:
  virtual void fillData() = 0;
};

class U : public Timpl {
public: 
  virtual ~U() {}
protected: 
  virtual void fillData() {...} // fill 
};

typedef  shared_ptr<T> TPtr
typedef  shared_ptr<U> UPtr


TPtr tp = std::make_shared<U>();  
UPtr up = std::static_pointer_cast<U>(tp);    //<-- error here :
Run Code Online (Sandbox Code Playgroud)

错误:没有匹配函数来调用'static_pointer_cast(TPtr)'

注意:模板std :: __ shared_ptr <_Tp1,_Lp> std :: static_pointer_cast(const std :: __ shared_ptr <_Tp2,_Lp>&)

注意:模板参数扣除/替换失败:

注意:'TPtr {aka boost :: shared_ptr}'不是从'const std :: __ shared_ptr <_Tp2,_Lp>'派生的

解决此问题的方法:

混合std::shared_ptr使用boost::shared_ptr并不是一个好主意.

Ker*_* SB 9

是的,使用static_pointer_cast:

#include <memory>

struct T { virtual ~T() {} };
struct U : T {};

std::shared_ptr<T> pt = std::make_shared<U>();     // *pt is really a "U"

auto pu = std::static_pointer_cast<U>(pt);
Run Code Online (Sandbox Code Playgroud)

还有一个匹配std::dynamic_pointer_cast,如果转换不可能,则返回空指针.