I am trying to implement a reasonable iterator interface, but the STL has me a little confused. Let's say we have defined the following (somewhat nonsensical) function:
Code:
#include <cstdlib>
template <typename ForwardIterator>
ForwardIterator write_char(int ch, std::size_t count, ForwardIterator next, ForwardIterator eof) {
while (count--) {
if (next == eof)
return ForwardIterator();
*next++ = ch;
}
return next;
}
The iteration policy seems pretty reasonable to me. Compare with operator ==, dereference once, and return the updated position. In the case where iterator "hits the wall", return a default-initialized instance of the iterator type.
Then we invoke it like this:
Code:
#include <iostream>
using namespace std;
int main() {
char buf[5] = {0};
char* end = buf + sizeof(buf);
char* pos = write_char('1', 3, buf, end);
cout << "buf: '" << buf << "' (" << (pos - buf) << " chars written)" << endl;
char* uho = write_char('!', 3, pos, end);
if (uho == NULL)
cout << "Error: buffer is full!" << endl;
}
So far, so good...or so I thought. Let's try it with "std::back_inserter":
Code:
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main() {
string buf;
auto pos = write_char('?', 3, back_inserter(buf), back_inserter());
}
Well that doesn't compile. There is no default constructor for "back_inserter" and you can't even compare them with each other either. I am obviously using the wrong STL object here. But what to use? Surely there is a way to put this all together into a generic interface?