Search code examples
c++templatesinheritancelanguage-lawyername-lookup

Is this-> mandatory to access Base<T> identifiers from derived classes?


This code compiles with MSVC 2015, but doesn't compile with Clang 5.0.0 (trunk 304874):

template <typename T>
struct Base
{
  T data;
};

template <typename T>
struct Derived : Base<T>
{
  auto getData() const
  {
    return data;
  }
};

Replacing data with this->data in Derived::getdata() makes Clang happy.

Which compiler is correct according to the C++ standard?

Must this-> be used in template code to access an identifier of a base class?


Solution

  • Clang is correct.

    $17.6.2/3 Dependent names [temp.dep]

    In the definition of a class or class template, the scope of a dependent base class is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

    For return data;, data is unqualified, then unqualified name lookup will be employed. This means the name in the base class Base<T> (which is a dependent base class because it depends on the template parameter T) shouldn't be found; i.e. the non-dependent names are not looked up in dependent base classes.

    this->data or Base<T>::data makes it qualified. This means the name will be looked up at the time of instantiation, and at that time the exact base specialization that must be explored will be known.