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?
An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.
The iterator is implemented as a pointer to a node, and contains operator overloads for the four usual iterator operations of dereference, increment, comparison, and assignment. in the list class that can be used to insert new data items at arbitrary locations in the list.
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With