Simple question: How do I get this to work?
struct A {
double whatever;
std::unordered_map<std::string, A> mapToMoreA;
}
g++ error: std::pair<_T1, _T2>::second has incomplete type
As far as I understand, when instantiating the map, the compiler needs to know the size of A, but it doesn’t know this because the map is declared in A’s declaration, so is the only way to get around this to use pointers to A (don’t feel like doing that)?
Most of the time it will depend on the container implementation details (more precisely, on what gets instantiated at the point of container declaration and what doesn’t). Apparently,
std::unordered_mapimplementation requires the types to be complete. At the same time GCC’s implementation ofstd::mapcompiles perfectly fine with incomplete type.To illustrate the source of such difference, consider the following example. Let’s say we decided to make our own naive implementation of
std::vector-like functionality and declared our vector class as followsAs long as our class definition contains only pointers to
T, the typeTis not required to be complete for the class definition itself. We can instantiatemy_vectoritself for an incompleteTwithout any problemsThe “completeness” of the type would be required later, when we begin to use (and therefore instantiate) the individual methods of
my_vector.However, if for some reason we decide to include a direct instance of
Tinto our vector class, things will chahgeNow the completeness of
Twill be required very early, at the point of instantiation ofmy_vectoritselfSomething like that must be happening in your case. The definition of
unordered_mapyou are dealing with somehow contains a direct instance ofA. Which is the reason why it is impossible to instantiate (obviously, you would end up with infinitely recursive type in that case).A better thought through implementation of
unordered_mapwould make sure not to includeAinto itself as a direct member. Such implementation would not requireAto be complete. As you noted yourself, Boost’s implementation ofunordered_mapis designed better in this regard.