Overloading *(iterator + n) and *(n + iterator) in a C++ iterator class?
- by exscape
(Note: I'm writing this project for learning only; comments about it being redundant are... uh, redundant. ;)
I'm trying to implement a random access iterator, but I've found very little literature on the subject, so I'm going by trial and error combined with Wikpedias list of operator overload prototypes.
It's worked well enough so far, but I've hit a snag.
Code such as
exscape::string::iterator i = string_instance.begin();
std::cout << *i << std::endl;
works, and prints the first character of the string. However, *(i + 1) doesn't work, and neither does *(1 + i).
My full implementation would obviously be a bit too much, but here's the gist of it:
namespace exscape {
class string {
friend class iterator;
...
public:
class iterator : public std::iterator<std::random_access_iterator_tag, char> {
...
char &operator*(void) {
return *p; // After some bounds checking
}
char *operator->(void) {
return p;
}
char &operator[](const int offset) {
return *(p + offset); // After some bounds checking
}
iterator &operator+=(const int offset) {
p += offset;
return *this;
}
const iterator operator+(const int offset) {
iterator out (*this);
out += offset;
return out;
}
};
};
}
int main() {
exscape::string s = "ABCDEF";
exscape::string::iterator i = s.begin();
std::cout << *(i + 2) << std::endl;
}
The above fails with (line 632 is, of course, the *(i + 2) line):
string.cpp: In function ‘int main()’:
string.cpp:632: error: no match for ‘operator*’ in ‘*exscape::string::iterator::operator+(int)(2)’
string.cpp:105: note: candidates are: char& exscape::string::iterator::operator*()
*(2 + i) fails with:
string.cpp: In function ‘int main()’:
string.cpp:632: error: no match for ‘operator+’ in ‘2 + i’
string.cpp:434: note: candidates are: exscape::string exscape::operator+(const char*, const exscape::string&)
My guess is that I need to do some more overloading, but I'm not sure what operator I'm missing.