Search code examples
c++templatesstliteratorvirtual

C++ virtual method that takes STL-style iterators


I want to have an interface ModelGenerator which has a method generate() that takes an iterable list of Evidence and creates a Model. Using the STL pseudo-duck-typing iterator idiom...

template<class Model>
class ModelGenerator {
  public:
    template<class Iterator>
    virtual bool generate(Iterator begin, Iterator end, Model& model) = 0;
};

But virtual functions can’t be templated. So I have to template the whole class:

template<class Model, class Iterator>
class ModelGenerator {
  public:
    virtual bool generate(Iterator begin, Iterator end, Model& model) = 0;
};

Ideally what I’d like to do is something like this...

template<class Model, class Evidence>
class ModelGenerator {
  public:
    virtual bool generate(iterator<Evidence>& begin,
                          iterator<Evidence>& end,
                          Model& model) = 0;
};

But there is no such interface that iterators inherit from. (The class std::iterator only contains a bunch of typedefs, no methods.)

The only way I can think of doing it is to give ModelGenerator a method addEvidence() which adds them one by one before calling generate(), but then I have to give the ModelGenerator state which is a bit of a pain.

How can I write a virtual method that takes any STL container?


Solution

  • You seem to need an any_iterator. That's an iterator that performs type erasure to insulate you from the actual iterator implementation.

    Adobe has an implementation of any_iterator: http://stlab.adobe.com/classadobe_1_1any__iterator.html

    Boost has an implementation of any_range: http://www.boost.org/doc/libs/1_49_0/libs/range/doc/html/range/reference/ranges/any_range.html