I'm trying to use member variables of a templated base class in a derived class, as in this example:
template <class dtype>
struct A {
int x;
};
template <class dtype>
struct B : public A<dtype> {
void test() {
int id1 = this->x; // always works
int id2 = A<dtype>::x; // always works
int id3 = B::x; // always works
int id4 = x; // fails in gcc & clang, works in icc and xlc
}
};
gcc and clang are both very picky about using this variable, and require either an explicit scope or the explicit use of "this". With some other compilers (xlc and icc), things work as I would expect. Is this a case of xlc and icc allowing code that's not standard, or a bug in gcc and clang?
Inheriting from a template classIt is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.
The derived class can inherit data members, member functions of base class. If the data members are public, they can be accessed by derived class, same class and outside the class. If data members are protected, they can be accessed by derived and same class only, but outside the class, they can not be accessed.
Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class.
You are probably compiling in non-strict mode in icc. Anyway, since x
is unqualified, it shall not be looked up in any base classes that depend on the template parameters. So in your code, there is no place where x
is found, and your code is invalid.
The other names are looked up using another form of lookup (class member access lookup, and qualified lookup). Both of those forms will look into dependent base classes if they can (i.e if they are dependent, and are thus looked up when instantiating the template when dtype
is known - all your other names are dependent on template parameters).
Even GCC in their latest versions don't implement that correctly, and some dependent names still resolve against dependent bases during unqualified lookup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With