C++ templates hides parent members

c++, generics, templates

Solution

You can also do

class B : public A<T> {
    int getA() {return this->a;}
};

The problem is that the member is in a base, which depends on a template parameter. Normal unqualified lookup is performed at the point of definition, not at the point of instantiation, and therefore it doesn't search dependent bases.

Problem

Usually, when `A` is inheriting from `B`, all the members of `A` are automatically visible to `B`'s functions, for example ``` class A { protected: int a; }; class B : public A { int getA() {return a;} //no need to use A::a, it is automatically visible }; ``` However when I'm inheriting with templates, this code becomes illegal (at least in `gcc`) ``` template<typename T> class A { protected: int a; }; template<typename T> class B : public A<T> { int getA() {return a;} }; templt.cpp: In member function `int B<T>::getA()': templt.cpp:9: error: `a' undeclared (first use this function) templt.cpp:9: error: (Each undeclared identifier is reported only once for each function it appears in.) ``` I must do one of ``` class B : public A<T> { using B::a; int getA() {return a;} }; class B : public A<T> { using A<T>::a; int getA() {return a;} }; class B : public A<T> { int getA() {return B::a;} }; ``` etc. As if the variable `a` is hidden by another variable of `B`, in the following case: ``` class HiddenByOverload {void hidden(){}} class HidesByOverload : public HiddenByOverload { void hidden(int i) {} //different signature, now `hidden` is hidden void usehidden() { HiddenByOverload::hidden(); // I must expose it explicitly } } ``` Why is it so? Are there any other ways to prevent C++ from hiding the parent template class' variables? Edit: thanks for everyone for the fascinating discussion. I must admit I didn't follow the argument which quoted paragraphs from the C++ standard. It's hard for me to follow it without reading the actual source. The best thing I can do to summarize the discussion, is quoting a short line from "The Zen of Python": If the implementation is hard to explain, it's (probably) a bad idea.

Original source