I tried three iterations of the following simple program. This is a highly simplified attempt to write a container-and-iterator pair of classes, but I was running into issues with incomplete types (forward declarations). I discovered that this was in fact possible once I templatized everything - but only if I actually used the template parameter! (I realized this by looking at the Google sparsetable code.)
Any hints explaining why the second works while the third doesn't? (I know why the first one doesn't work - the compiler needs to know the memory layout of the container.)
Thanks in advance.
// This doesn't work: invalid use of incomplete type.
#if 0
struct container;
struct iter {
container &c;
int *p;
iter(container &c) : c(c), p(&c.value()) {}
};
struct container {
int x;
int &value() { return x; }
iter begin() { return iter(*this); }
};
int main() {
container c;
c.begin();
return 0;
}
#endif
// This *does* work.
template<typename T> struct container;
template<typename T> struct iter {
container<T> &c;
T *p;
iter(container<T> &c) : c(c), p(&c.value()) {}
};
template<typename T> struct container {
T x;
T &value() { return x; }
iter<T> begin() { return iter<T>(*this); }
};
int main() {
container<int> c;
c.begin();
return 0;
};
// This doesn't work either.
#if 0
template<typename T> struct container;
template<typename T> struct iter {
container<int> &c;
int *p;
iter(container<int> &c) : c(c), p(&c.value()) {}
};
template<typename T> struct container {
int x;
int &value() { return x; }
iter<int> begin() { return iter<int>(*this); }
};
int main() {
container<int> c;
c.begin();
return 0;
}
#endif