Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to protected members of base class with CRTP

I would like to ask you a question about the 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 (e.g., "foo")?

The compiler tells me: error: ‘value’ was not declared in this scope

#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;
}
like image 982
user3903079 Avatar asked Oct 15 '25 17:10

user3903079


1 Answers

Because you are directly inheriting from a base class that depends on T you need to use this-> to access your data members:

std::cout << "Its own value is : " << this->value << std::endl;
//                                    ^^^^^^
like image 103
David G Avatar answered Oct 18 '25 05:10

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!