铸造列表< 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的注释)是正确的 - 列表是完全不相关的类型。 >
- 首先使用
列表< A *>
,即使你知道动态类型是B * $ c>或
或
C *
- 在< code& ,它转换为/来自正确的动态类型 - 这相当于Java泛型中的(un)boxing行为
-
重写
doSomething
作为函数模板,其唯一的约束是类型是可转换的
- use
list<A*>
everywhere in the first place, even when you know the dynamic type isB*
orC*
- 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 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