如何投射shared_ptr <foo <derived>&gt;到shared_ptr <foo <base>&gt;?</foo <base> </foo <derived>

时间:2014-03-05 22:07:00

标签: c++ boost c++11

我需要将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)

Test Code

1 个答案:

答案 0 :(得分:4)

具有不同参数的类模板被C ++类型系统视为完全不同的类型。

Foo<Base>

的类型不同
Foo<Derived>

并且它们之间没有多态关系。