7

クラス U と T の 2 つの 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 :

エラー: '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

4

1 に答える 1

12

はい、使用します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);

std::dynamic_pointer_cast変換が不可能な場合に null ポインターを返すマッチングもあります。

于 2013-11-12T15:05:26.027 に答える