简体   繁体   English

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

[英]Access to protected members of base class with CRTP

I would like to ask you a question about the CRTP. 我想问你一个关于CRTP的问题。 Suppose you have a base class and a derived class as below. 假设您有一个基类和派生类,如下所示。 Is there a way to extract the member "value" from the base class in one of the member functions of the derived class (eg, "foo")? 有没有办法从派生类的一个成员函数(例如“foo”)中的基类中提取成员“value”?

The compiler tells me: error: 'value' was not declared in this scope 编译器告诉我:错误:在此范围内未声明'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;
}

Because you are directly inheriting from a base class that depends on T you need to use this-> to access your data members: 因为您直接从依赖于T的基类继承,所以您需要使用this->来访问您的数据成员:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问孙类中受保护的基类成员 - Access protected members of base class in grandchild class 使用CRTP访问派生类的受保护成员 - Accessing protected members of derived class with CRTP 从派生类访问基类的受保护数据成员 - Access protected data members of the base class from the derived class 为什么派生类无法访问受保护的基类成员? - Why the derived class cannot access protected base class members? 无法访问派生类中的基类保护成员! (在虚函数中) - Not able to access base protected members in derived class ! ( in virtual functions ) 使用指向派生类中基类的指针访问受基类保护的成员 - Access base class protected members using pointers to base class in derived class 为什么我不能使用受保护/私有继承在派生实例中访问基类的受保护成员? - Why can't I access protected members of base class in derived instances using protected/private inheritance? 如何通过将对象传递给另一个派生 class 来访问其派生 class 的基础 class 的受保护数据成员 - How to access protected data members of base class of its derived class by passing objects to another derive class 受保护的继承是否允许派生类访问其基类的私有成员? - Does protected inheritance allow the derived class access the private members of its base class? CRTP访问受保护的CTOR派生 - CRTP access to protected CTOR in derived
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM