Re: template metaprogramming and recursive inheritance
On 1 Okt., 16:29, Christof Warlich <cwarl...@gmx.de> wrote:
template <int x> struct S;
template <> struct S<0> {
S<0>(void): y(0) {}
int y;};
template <int x> struct S: public S<x - 1> {
S<x>(void) {y++;}
};
The error that I get is:
In constructor 'S<x>::S()':
7: error: 'y' was not declared in this scope
For my understanding, the error message is simply wrong.
The error message is correct, see FAQ:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19
Imagine instantiating
S<2> s;
This causes S<1> and S<0> to be instantiated as well due
to the recursive inheritance. Thus, y is finally provided
by the template specialization defined for S<0>, which in
turn is an indirect base of S<2>.
Could this be a compiler bug? I'm using g++ 4.1.2.
The compiler is right and the reason is that by deriving
S<x> from S<x - 1> the base class is a type-dependent and
the compiler is not allowed to assume anything about it's
members (Or to say: Name look-up does not occur in the
dependent base classes), since there is no guarantee that
they will exist (you can change the definition of an
arbitrary S<z> by explicit or partial specialization over
a set of z).
To ensure that the compiler does not *immediatly* try to
resolve the entity named "y" inside the scope of S<x>, you
make itself a type-dependent expression, e.g. by replacing
the unqualified y by
this->y
or by
S::y (or S<x> or S<x - 1>)
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]