使用CRTP访问基类的受保护成员

use*_*079 3 c++ protected derived-class crtp

我想问一个关于CRTP的问题。假设您有一个基类和一个派生类,如下所示。有没有一种方法可以从派生类的成员函数之一(例如“ foo”)的基类中提取成员“ value”?

编译器告诉我:错误:在此范围内未声明“值”

#include <iostream>

template <class T, class Implementation>
class FooBase
{
protected:
   void fooBase(void) {};
   int value;
};

template <class T>
class Foo : public FooBase <T, Foo<T>>
{
  friend FooBase <T, Foo<T>>;

  public:
  void foo()
  {
    std::cout << "Its own value is : " << value << std::endl;
  }
};

int main ()

{
  Foo <int> foo;
  foo.foo();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 6

因为您是直接从依赖的基类继承的,所以T需要使用它this->来访问数据成员:

std::cout << "Its own value is : " << this->value << std::endl;
//                                    ^^^^^^
Run Code Online (Sandbox Code Playgroud)