我好奇地重复使用模板时遇到以下问题,当我尝试访问CRTP基类的数据成员时遇到了问题.
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();
}
上面的代码可以编译并正常运行,可以打印出“ 10”,但是如果我将派生类模板化,例如:
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();
}
类A只是用作模板参数的虚拟类.但是编译器抱怨找不到“ protectedData”.错误信息如下:
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;
解决方法:
它实际上与CRTP无关,而是与以下事实有关:对于依赖库访问派生代码,您需要限定条件.
将行更改为
std::cout<<this->protectedData<<std::endl;
解决了.
参见accessing a base class member in derived class.