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

Access to protected members of base class with CRTP

本文关键字:受保护 成员 基类 CRTP 访问 使用      更新时间:2023-10-16

我想问你一个关于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;
}

因为你直接继承了一个依赖于T的基类,所以你需要使用this->来访问你的数据成员:

std::cout << "Its own value is : " << this->value << std::endl;
//                                    ^^^^^^