There is a code like this:
#include <iostream>
This is a wrapper for std::vector
with my extra features. I would like to use the std::vector
iterator, however I only want to change the operator*
behavior for the iterator:
T& operator*(){ // do some additional function // normal behavior, return value of some element in vector ?? }
How can I use std::vector
and its iterator with a modification of only operator*
? I would also like to wrap functions like begin()
and end()
for an iterator, how do I wrap them correctly?
EDIT:
Using the answer tips in this section, I managed to solve my problem as follows:
#include <iostream> #include <vector> template <class T> class A { public: class iterator : public std::vector<T>::iterator { public: iterator(typename std::vector<T>::iterator c) : std::vector<T>::iterator(c) { } T& operator*() { std::cout << "Im overloaded operator*\n"; return std::vector<T>::iterator::operator *(); } }; iterator begin() { return iterator(v.begin()); } iterator end() { return iterator(v.end()); } void add(const T& elem) { v.push_back(elem); } private: std::vector<T> v; }; int main() { A<int> a; a.add(2); a.add(4); for (A<int>::iterator it = a.begin(); it != a.end() ; ++it) { std::cout << *it << std::endl; } return 0; }
Perhaps this will be useful for someone.
scdmb source share