Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

stl - C++: How do I pass a container of derived classes to a function expecting a container of their base classes?

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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();
    }
}

Then chug can take any container of any type, as long as it's a container of pointers and has a chug method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...