Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a class which can be constructed with an input iterator?

Tags:

c++

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).

like image 271
VF1 Avatar asked Sep 06 '25 03:09

VF1


1 Answers

Your class should have a templated constructor (templated on the iterator type):

class my_class {

    template <typename InputIterator>
    my_class(InputIterator first, InputIterator last) {
        // ...
    }

    // ...
};
like image 143
Cassio Neri Avatar answered Sep 07 '25 21:09

Cassio Neri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!