4

I have the following problem with the curiously recurring template, with a problem when I try to access the data member of CRTP base class.

template<typename T>
struct Base {
  int protectedData=10;
};

struct Derived : public Base<Derived> {
public:
  void method() {
    std::cout<<protectedData<<std::endl;
  };
};

int main ()
{
  Derived a;
  a.method();
}

The above code compiles and runs fine and I can get "10" printed, but if I have the derived class templated, like:

template<typename T>
struct Base {
  int protectedData=10;
};

template<typename T>
struct Derived : public Base<Derived<T> > {
public:
  void method() {
    std::cout<<protectedData<<std::endl;
  };
};

class A{};

int main ()
{
  Derived<A> a;
  a.method();
}

class A is just a dummy class served as the template parameter. But the compiler complains cannot find the "protectedData". The error information is as following:

g++-4.9 test.cc -Wall -std=c++1y -Wconversion -Wextra
test.cc: In member function ‘void Derived<T>::method()’:
test.cc:26:11: error: ‘protectedData’ was not declared in this scope
    cout<<protectedData<<endl;
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185

1 Answers1

5

It doesn't really have to do with CRTP, but rather with the fact that for dependent-base-accessing derived code, you need to qualify things.

Changing the line to

std::cout<<this->protectedData<<std::endl;

solved it.

See Derived template-class access to base-class member-data.

Hari
  • 1,561
  • 4
  • 17
  • 26
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185