Reputation: 1652
The std::vector
class has a convenient constructor which allows any input iterator for its parameter. I would like to implement a similar pattern in my own class, because the class needs to take in some collection when instantiated, but I would like to have the iterator over that collection for encapsulation purposes. One way that I thought of to do this is template-ing the whole class with the input iterator type, but that can't be what STL does, because vector
is clearly only templated with the type being iterated over. Of course, one option is a templated generator function, but I'd really like to know how it's done by compilers that implement STL - somehow, the InputIterator
type is a typename specific only to the constructor, even if constructors can't be templated.
(Yes, I have tried to look at vector.tpp
but I could not understand it).
Upvotes: 4
Views: 341
Reputation: 20513
Your class should have a templated constructor (templated on the iterator type):
class my_class {
template <typename InputIterator>
my_class(InputIterator first, InputIterator last) {
// ...
}
// ...
};
Upvotes: 6