我需要将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)
答案 0 :(得分:4)
具有不同参数的类模板被C ++类型系统视为完全不同的类型。
Foo<Base>
与
的类型不同Foo<Derived>
并且它们之间没有多态关系。