Joshua Chia
Joshua Chia

Reputation: 1968

C++ class template inheritance puzzle

What's wrong with this code? gcc 4.6.1 is complaining "‘foo’ was not declared in this scope" in baz(). If I transform the code so that one of the templates is just a regular class, the problem goes away.

struct Foo {
    char foo;
};

template<int N>
struct Bar : public Foo
{
    Bar() { foo; }
};

template<int N>
struct Baz : public Bar<N>
{
    void baz() { foo; }
};

int main() {
    Baz<10> f;
    return 0;
}

Upvotes: 0

Views: 334

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

foo is a dependent name; that is, it depends on the template parameter, so until the template is instantiated the compiler doesn't know what it is. You have to make it clear that it is a class member, either Bar<N>::foo or this->foo.

(You probably also want to do something with it; simply using it as the ignored value of an expression doesn't do anything at all).

Upvotes: 1

lvella
lvella

Reputation: 13443

What is wrong, according to the specifications, I don't know, but you may make your code to compile by using:

void baz() { Bar<N>::foo; }

Upvotes: 1

Related Questions