派生类模板化时访问基础成员数据错误

问题描述 投票:0回答:1

我对奇怪的重复模板有以下问题,当我尝试访问 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;
c++ templates template-meta-programming
1个回答
5
投票

它实际上与 CRTP 无关,而是与这样一个事实有关,即对于依赖基访问的派生代码,您需要限定一些东西。

换行到

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

解决了。

参见派生模板类访问基类成员数据

© www.soinside.com 2019 - 2024. All rights reserved.