C++:如何将派生类的容器传递给期望其基类容器的函数?

2022-01-24 00:00:00 containers polymorphism c++ stl

嗨!任何人都知道我如何使下面代码中的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
"; }
};

class Derived : public Base
{
public:
    virtual void chug() { cout << "Derived chug
"; }
    void foo() { cout << "Derived foo
"; }
};

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 成为一个模板函数(免责声明:我不在带有编译器的计算机上,所以我没有尝试编译它):

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.

相关文章