c++ - Range-for loop recognizes wrong type (C2440) -


the c2440 error (cannot convert 'char' 'text_iterator' occurring on line):

void print(document& d) {     (text_iterator p : d) cout << *p; } 

replacing 'text_iterator' 'auto' gives 'illegal indirection' error (dereferenced type must pointer).

class document has begin() , end() functions defined (returning text_iterator), , text_iterator has usual iterator operators. here code:

class text_iterator {     list<line>::iterator ln;     line::iterator pos; public:     // . . .      char& operator*() { return *pos; }     text_iterator& operator++();      // . . . }; 

and document:

struct document {     list<line> line;      text_iterator begin()     {         // . . .     }      text_iterator end()     {         // . . .     }      // . . . }; 

you using incorrect type loop variable. variable not iterator of container iterator of container points to.

if had

std::vector<int> foo(10); 

and want use ranged based loop use

for (int e : foo) // or (auto e : foo)      std::cout << e << " "; 

you not use

for (std::vector<int>::iterator e : foo)     std::cout << *e << " "; 

so need use whatever text_iterator points instead of text_iterator. in case

void print(document& d) {     // if p cheap copy     (auto p : d) cout << p;     // if p expensive copy     (const auto& p : d) cout << p; } 

should work.


Comments