我对奇怪的重复模板遇到以下问题,当我尝试访问 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;
解决了它。
See 派生模板类对基类成员数据的访问.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)