cast listlt;A*gt; to listlt;B*gt; where B inherits A(演员表lt;A*gt;列出lt;B*gt;其中 B 继承 A)
问题描述
我有一个函数
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.
选项有:
- 首先在任何地方使用
list<A*>,即使您知道动态类型是B*或C* - 在
list<A*>上编写一个包装器,该包装器可以转换为正确的动态类型/从正确的动态类型转换 - 这相当于 Java 泛型中的(取消)装箱行为 将
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
doSomethingas 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
这篇关于演员表<A*>列出<B*>其中 B 继承 A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:演员表<A*>列出<B*>其中 B 继承 A
基础教程推荐
- C++多态 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 对 STL 容器的安全并行只读访问 2022-10-25
- 总计将在节日礼物上花多少钱 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- C语言数组 1970-01-01
- C语言3个整数的数组 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
