【发布时间】:2014-03-06 11:21:44
【问题描述】:
我需要将shared_ptr<Foo<Derived> > 转换为shared_ptr<Foo<Base> >,但不知道该怎么做。基本上我想做:
shared_ptr<Foo<Base>> p (new Foo<Derived>());
但是编译器报错:
/usr/include/c++/4.8/bits/shared_ptr_base.h: In instantiation of 'std::__shared_ptr<_Tp, _Lp>::__shared_ptr(_Tp1*) [with _Tp1 = Foo<Derived> _Tp = Foo<Base> __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]':
/usr/include/c++/4.8/bits/shared_ptr.h:113:32: required from 'std::shared_ptr<_Tp>::shared_ptr(_Tp1*) [with _Tp1 = Foo<Derived> _Tp = Foo<Base>]'
main.cpp:17:48: required from here
/usr/include/c++/4.8/bits/shared_ptr_base.h:768:39: error: cannot convert 'Foo<Derived>*' to 'Foo<Base>*' in initialization
: _M_ptr(__p), _M_refcount(__p)
【问题讨论】:
-
一般来说这是无法做到的,因为
Foo<Base>和Foo<Derived>是不相关的类型。如果您想要更好的建议,您必须解释Foo的实际用途。 -
因为
Foo<T>不是从Foo<U>派生的。 -
@BrianBi 相关问题:stackoverflow.com/questions/22209367/… 虽然没有人回答,所以我把它放在上面更简单的方式。