0

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;
}
4
  • 2
    I did not understand what you are trying to do here - Bar() {foo;} What is foo? Commented Oct 31, 2011 at 18:57
  • This is called dependent name. See womble.decadent.org.uk/c++/template-faq.html#base-lookup Commented Oct 31, 2011 at 19:00
  • possible duplicate of Why doesn't this C++ template code compile? Commented Oct 31, 2011 at 19:02
  • badmaash, you sound like a compiler. :) foo is the foo from the class Foo, inherited by Bar, of course. Commented Feb 24, 2012 at 22:27

2 Answers 2

1

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

What is wrong, is that while compiling Baz it doesn't know which Bar<N> to inherit from yet (there might be specializations later), so it doesn't yet know there is a foo member. By qualifiying it, you're telling it that Bar<N> will have the foo member, and not to worry about it until N is known.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.