Accessing base member data error when derived class is templated

纵然是瞬间 提交于 2019-12-20 04:28:13

问题


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;

回答1:


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 accessing a base class member in derived class.



来源:https://stackoverflow.com/questions/30930923/accessing-base-member-data-error-when-derived-class-is-templated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!