Are the base members of the template class class not visible in the derived template class?

Consider the following C ++ code,

template <typename Derived> struct A { bool usable_; }; template <typename Derived> struct B : A< B<Derived> > { void foo() { usable_ = false; } }; struct C : B<C> { void foo() { usable_ = true; } }; int main() { C c; } 

I got a compilation error: in the member function void B<Derived>::foo() :

template_inherit.cpp: 12: error: "usable_" was not declared in this scope.

Why? Any good fix?

+6
source share
1 answer

This is because usable_ is an optional name, so it is looked up during the analysis of the template, instead of looking for it when creating the instance (when the base class is known).

An unqualified name lookup will not look up, and immutable names will never look up in dependent base classes. You can make usable_ dependent as follows, which also usable_ for an unqualified name.

 this->usable_ = false; // equivalent to: A<B>::usable_ = false; A< B<Derived> >::usable_ = false; B::usable_ = false; 

All this will work. Or you can declare a name in a derived class using the declaration declaration

 template <typename Derived> struct B : A< B<Derived> > { using A< B<Derived> >::usable_; void foo() { usable_ = false; } }; 

Note that there will be no problems in C - this only affects B

+13
source

All Articles