shared_ptr 的隐式转换 [英] Implicit conversion of shared_ptr
问题描述
我有两个类 U 和 T 的 shared_ptr,其中 T 是 U 的基础.
I have two shared_ptrs of the classes U and T where T is the base of U.
从shared_ptr
到shared_ptr
的隐式转换是没有问题的.但是也可以将 shared_ptr
转换为 shared_ptr
?
It is no problem to do an implicit conversion from shared_ptr<U>
to shared_ptr<T>
.
But is is also possible to do a conversion from shared_ptr<T>
to shared_ptr<U>
?
我尝试了建议的解决方案:
I tried the sugested solution:
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)'
error: no matching function for call to 'static_pointer_cast(TPtr)'
注意:模板 std::__shared_ptr<_Tp1, _Lp> std::static_pointer_cast(const std::__shared_ptr<_Tp2, _Lp>&)
note: template std::__shared_ptr<_Tp1, _Lp> std::static_pointer_cast(const std::__shared_ptr<_Tp2, _Lp>&)
注意:模板参数推导/替换失败:
note: template argument deduction/substitution failed:
注意:'TPtr {aka boost::shared_ptr}' 不是从 'const std::__shared_ptr<_Tp2, _Lp>' 派生的
note: 'TPtr {aka boost::shared_ptr}' is not derived from 'const std::__shared_ptr<_Tp2, _Lp>'
此问题的解决方案:
将 std::shared_ptr
与 boost::shared_ptr
混合起来不是个好主意.
mixing of std::shared_ptr
with boost::shared_ptr
is no good idea.
推荐答案
是的,使用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
如果无法转换,它会返回一个空指针.
There's also a matching std::dynamic_pointer_cast
which returns a null pointer if the conversion isn't possible.
这篇关于shared_ptr 的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!