【问题标题】:How to cast shared_ptr<Foo<Derived> > to shared_ptr<Foo<Base> >?如何将 shared_ptr<Foo<Derived>> 转换为 shared_ptr<Foo<Base> >?
【发布时间】:2014-03-06 11:21:44
【问题描述】:

我需要将shared_ptr&lt;Foo&lt;Derived&gt; &gt; 转换为shared_ptr&lt;Foo&lt;Base&gt; &gt;,但不知道该怎么做。基本上我想做:

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

【问题讨论】:

  • 一般来说这是无法做到的,因为Foo&lt;Base&gt;Foo&lt;Derived&gt; 是不相关的类型。如果您想要更好的建议,您必须解释 Foo 的实际用途。
  • 因为Foo&lt;T&gt; 不是从Foo&lt;U&gt; 派生的。
  • @BrianBi 相关问题:stackoverflow.com/questions/22209367/… 虽然没有人回答,所以我把它放在上面更简单的方式。

标签: c++ boost c++11


【解决方案1】:

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

Foo<Base>

与 a 的类型不同

Foo<Derived>

它们之间没有多态关系。

【讨论】:

  • 虽然我在 C++ 标准中找不到合适的引用
  • 这很难,为什么它会提到不相关的东西?它描述了相关的事物,而不是所有无关的事物!
  • @Yakk 在标准涵盖的每个主题中都介绍了许多合法事物以及绝对非法事物的示例。在模板下寻找涵盖该主题的示例是明智的,因为我们中的许多人最初可能认为这种转换是可能的。
  • 根据Foo 的实际作用,总是可以定义 特化template&lt;&gt; struct Foo&lt;Derived&gt; : Foo&lt;Base&gt; ...。但是,上次我这样做时,像这样玩弄整个类层次结构真是令人头疼(如果不写下来就不可能跟踪关系),所以我决定以后避免这样做。
  • 所以,有一种方法可以解决 OP 的问题:specialize shared_ptr。从 1 分到过度杀戮,就是过度杀戮。
猜你喜欢
  • 2017-08-06
  • 2010-11-24
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
相关资源
最近更新 更多