Chris G
Chris G

Reputation: 469

Creating a method to iterate over any container of a custom class with templates?

I have an abstract class of Animal, of which i've created sub classes like Dog, Cat, Hamster, etc.

I've made a method that iterates over a list of animal objects and calls the 'describe' method on each of them. Describe is a pure virtual function, that has been implemented in the sub classes.

I'm trying to create a method that iterates over any container of animal and does the same thing.

Here's what I have so far:

template <typename Container>
void describe_all(Container &c) {
typedef typename Container::iterator Iter;

for (Iter p = c.begin(); p != c.end(); ++p)


}

My mind goes blank here and i'm unsure how to incorporate the animal class. I'm still pretty new to C++!

Upvotes: 2

Views: 1459

Answers (2)

Nil
Nil

Reputation: 2390

You already have the answer. Just type the call to describe()

template <typename Container>
void describe_all(const Container &c) {
    typedef typename Container::iterator Iter;

    for (Iter p = c.begin(); p != c.end(); ++p)
        (*p)->describe();
    }
}

It won't compile if the templated type doesn't offer a describe method.

Of course, if you can use C++11, this code would be cleaner.

template <typename Container>
void describe_all(const Container &c) {
    for (auto ptr; c)
        ptr->describe();
    }
}

Upvotes: 6

Steve
Steve

Reputation: 1510

You might be interested in the for_each() in stl.

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f) {
  for( ; first != last; ++first)
    f(*first);
  return f;
}

Upvotes: 2

Related Questions