C ++:如何将一个派生类的容器传递给一个需要它们的基类的容器的函数? [英] C++: How do I pass a container of derived classes to a function expecting a container of their base classes?
问题描述
HI!任何人都知道我可以在下面的代码中行 chug(derlist);
工作?
HI! Anyone know how I can make the line "chug(derlist);
" in the code below work?
#include <iostream>
#include <list>
using namespace std;
class Base
{
public:
virtual void chug() { cout << "Base chug\n"; }
};
class Derived : public Base
{
public:
virtual void chug() { cout << "Derived chug\n"; }
void foo() { cout << "Derived foo\n"; }
};
void chug(list<Base*>& alist)
{
for (list<Base*>::iterator i = alist.begin(), z = alist.end(); i != z; ++i)
(*i)->chug();
}
int main()
{
list<Base*> baselist;
list<Derived*> derlist;
baselist.push_back(new Base);
baselist.push_back(new Base);
derlist.push_back(new Derived);
derlist.push_back(new Derived);
chug(baselist);
// chug(derlist); // How do I make this work?
return 0;
}
我需要这个的原因基本上是,我有一个非常复杂的对象,我需要传递给某些函数,只关心这些复杂对象中的一个或两个虚拟函数。
The reason I need this is basically, I have a container of very complex objects, which I need to pass to certain functions that only care about one or two virtual functions in those complex objects.
我知道简短的答案是你不能, 我真的在寻找人们用来解决这个问题的任何技巧/习语。
I know the short answer is "you can't," I'm really looking for any tricks/idioms that people use to get around this problem.
提前感谢。
推荐答案
您的问题很奇怪;该主题询问如何将物品放在容器中而不丢失多态性 - 但这是乞求的问题;容器中的项目不会丢失多态性。你只需要一个基本类型的容器,一切正常。
Your question is odd; the subject asks "how do I put items in a container without losing polymorphism" - but that is begging the question; items in containers do not lose polymorphism. You just have a container of the base type and everything works.
从你的示例,它看起来你要问是如何转换一个容器的子指针到基本指针的容器? - 答案是,你不能。子指针可以转换为基指针,子指针的容器不可以。它们是不相关的类型。虽然,请注意,shared_ptr 是可转换为shared_ptr,但只是因为他们有额外的魔法,使这项工作。容器没有这样的魔法。
From your sample, it looks what you're asking is "how do I convert a container of child pointers to a container of base pointers?" - and the answer to that is, you can't. child pointers are convertible to base pointers, containers of child pointers are not. They are unrelated types. Although, note that a shared_ptr is convertible to shared_ptr, but only because they have extra magic to make that work. The containers have no such magic.
一个答案是让chug一个模板函数(免责声明:我不是在一台带编译器的计算机上, t尝试编译这个):
One answer would be to make chug a template function (disclaimer: I'm not on a computer with a compiler, so I haven't tried compiling this):
template<typename C, typename T>
void chug(const C<T>& container)
{
typedef typename C<T>::iterator iter;
for(iter i = container.begin(); i < container.end(); ++i)
{
(*i)->chug();
}
}
然后chug可以取任何类型的任何容器只要它是指针的容器并且有一个chug方法。
Then chug can take any container of any type, as long as it's a container of pointers and has a chug method.
这篇关于C ++:如何将一个派生类的容器传递给一个需要它们的基类的容器的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!