演员表<A*>列出<B*>其中 B 继承 A

2022-01-24 00:00:00 containers templates casting c++ stl

我有一个函数

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

和类

class B : A  
class C : A

有没有像这样直接调用我的函数的方法

Is there a direct way to call my function like

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

或者我必须像手动包装它

or do I have to wrap it manually like

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*> 强制转换为 list<A*> 失败,我的猜测是由于模板专业化,编译器考虑 list<B*>list<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 的评论)是正确的 - 列表是完全不相关的类型.

Your intuition (and juanchopanza's comment) is correct - the lists are completely unrelated types.

选项有:

  1. 首先在任何地方使用 list<A*>,即使您知道动态类型是 B*C*
  2. list<A*> 上编写一个包装器,该包装器可以转换为正确的动态类型/从正确的动态类型转换 - 这相当于 Java 泛型中的(取消)装箱行为
  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

相关文章