Stylistic (somewhat) constructor question

I have written a tiny little (and stupid) iterator class, that's supposed to print the current line number on a specified ostream while reading from an istream. I first wanted to derive from std::istream_iterator, but the problem was that that way it's constructor would be invoked before I'd even get a chance to print something (of course that would only matter if I print and read from the console, but that was actually the main purpose here so that wasn't acceptable for me). My next attempt was to write static creator methods that would perform the printing of the line before invoking the constructor, but that a) made using the class less intuitive and b) would lead to inconsistencies, as I have of course no access to the member that's counting the current line before the object is created. So because I didn't like that approach either, I discarded the idea of inheriting from istream_iterator and rewrote the class so it would contain an istream_iterator rather than inheriting from it. Now I ran straight into the next problem though, that is that I actually initialize the iterator member twice, one time as an EOS iterator so it wouldn't start reading from the stream, and then again as an iterator of the passed stream after I printed the lines. This lead to about a dozen compiler warnings which I am not sure I should ignore or not.

Anyways, here is the current code, if anyone knows a good workaround that would be nice:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
template<typename T>
class istream_line_counter_iterator
{
public:
	istream_line_counter_iterator<T>(std::istream& in, std::ostream& outstream=std::cout) : it(), line_counter(0), out(outstream), isNotEOS(true)
	{
		nextLine();
		it = std::istream_iterator<T>(in);
	}
	istream_line_counter_iterator<T>() : it(), line_counter(0), out(std::cout), isNotEOS(false) {}
	istream_line_counter_iterator<T> operator++()
	{
		if(isNotEOS)
		{
			nextLine();
		}
		++it;
		if (it==std::istream_iterator<T>()) isNotEOS = false;
		return *this;
	}
	T operator*()
	{
		return *it;
	}
	bool operator!=(const istream_line_counter_iterator& right)
	{
		return this->it!=right.it;
	}
	bool operator==(const istream_line_counter_iterator& right)
	{
		return this->it==right.it;
	}
private:
	void nextLine()
	{
		++line_counter;
		std::cout<<"Line "<<line_counter<<": ";
	}
	bool isNotEOS;
	int line_counter;
	std::istream_iterator<T> it;
	std::ostream& out;
};


PS: I am aware this doesn't actually count the read lines. No need to comment about that.

EDIT: I just figured out I don't really need an istream_iterator here in the first place, so that kinda fixes my problem lol...
Last edited on
Topic archived. No new replies allowed.