铸造列表< A *>到列表< B *>其中B继承A [英] cast list<A*> to list<B*> where B inherits A

查看:189
本文介绍了铸造列表< A *>到列表< B *>其中B继承A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数

void doSomething(list<A*> list1, list<A*> list2)

和类

class B : A  
class C : A

方式调用我的函数,如

void doSomething(list<B*> listOfB, list<C*> listOfC)

或者我必须手动换行

void doSomething(list<B*> listOfB, list<C*> listOfC) {
  list<A*> l1;
  list<A*> l2;

  for (B* b : listOfB)
    l1.insert(b);

  for (C* c : listOfC)
    l2.insert(c);

  doSomething(l1, l2); //calling the function taking supertype
}

我试图不成功地转换 list< B *> 列表< A *> ,我的猜测是,由于模板专业化, c $ c> list< B *> 和列表< A *> 不相关,但是B继承A。

I tried unsuccessfully to cast list<B*> to list<A*>, my guess is that due to template specialization, the compiler consider list<B*> and list<A*> unrelated, however B inherits A.

有人可以确认这一点,或者以不同的方式来管理这个问题吗?

Can someone confirm this, or come with a different way to manage this problem ?

推荐答案

这些选项是:

    您的直觉(和juanchopanza的注释)是正确的 - 列表是完全不相关的类型。 >
  1. 首先使用列表< A *> ,即使你知道动态类型是 B * 或 C *

  2. 在< code& ,它转换为/来自正确的动态类型 - 这相当于Java泛型中的(un)boxing行为

  3. 重写 doSomething 作为函数模板,其唯一的约束是类型是可转换的

  1. use list<A*> everywhere in the first place, even when you know the dynamic type is B* or C*
  2. write a wrapper over list<A*> which casts to/from the correct dynamic type - this is equivalent to the (un)boxing behaviour in Java generics
  3. re-write doSomething as a function template whose only constraint is that the types be convertible

template <typename Sequence1, typename Sequence2>
void doSomething(Sequence1 &x, Sequence2 &y) {
  // require only that *x.begin() is convertible with *y.begin(), etc.
}

我也同意Kerrek的建议,应该使用迭代器,但不改变类型要求显着 - 您只需要获取两个迭代器类型的参数,而不是两个容器类型的参数

I'd also agree with Kerrek's suggestion that this should use iterators instead, but that doesn't change the type requirement significantly - you just get two iterator type params instead of two container type params

这篇关于铸造列表&lt; A *&gt;到列表&lt; B *&gt;其中B继承A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆