我需要投shared_ptr<Foo<Derived> >
到shared_ptr<Foo<Base> >
,但不知道如何。基本上我想要做的:如何将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 '和'Foo '是不相关的类型。如果你想得到更好的建议,你必须解释'Foo'实际上应该做什么。 –
Brian
因为'Foo'不是来自'Foo '。 –
Anthony
@BrianBi相关问题:http://stackoverflow.com/questions/22209367/use-cloudviewer-with-custom-pointt-type虽然没有人回答,所以我把它放在一个更简单的方式,如上所述。 – texasbruce