I cannot define a custom iterator over std::map<int,Foo>
because Foo is an "incomplete type". What is wrong and how can I fix it so the custom iterator is defined correctly?
More specifically, I have a map
object in another class Bar
:
struct Bar{
map<int,Foo> theMap;
};
Note that struct Bar
compiles fine, with no issues, in exactly the same file as the failed compile mentioned. If b
is an object of type Bar, I would like to be able to write:
for (Foo& foo:b) {...code using "foo"...}
which would bind foo
to each value in b.theMap
. To do this, I defined a custom iterator that encapsulates theMap::iter
like this:
struct myIterator{
map<int,Foo>::iterator originalMapIterator;
Foo& operator*(){return (*originalMapIterator).second;}
...operator++, operator== ,etc.
}
But when struct myIterator
is compiled, I get the error: "field has incomplete type 'Foo'" pointing to the map<int,Foo>::iterator
.
I realize that I could probably fix this issue by changing the map
to hold values of type unique_ptr(Foo)
. Maybe that is best, although it is a fair amount of code (Foo is about 500 bytes). Anyway, is there a way to fix the definition as is? It seems odd that a map<int,Foo>
is accepted fine by the compiler, but not a map<int,Foo>::iterator
. Anyway, I want to understand just what is going on here.
As for "incomplete type": I am not certain exactly what this means here or how to avoid it. The Foo
header file is included, what more would the compiler want? Why would it accept a map
and not a map::iterator
?
EDIT: I located the problem, see the answer.