Accessing protected members of derived class with CRTP

1k views Asked by At

I'm using CRTP, and I have a problem with accessing the protected members of derived class.

Here is example, close to my code:

template< typename Self>
  class A {
  public:
      void foo( ) {
          Self s;
          s._method( s); //ERROR, because _method is protected
      }

  protected:
      virtual  void _method( const Self & b) = 0;
  };

class B : public A< B> {
protected:
    void _method( const B & b) {}
};

I understood, that I must use friend keyword. But I can't understand where to put it in class A< Self>. I know that I could make void _method( const B &b) public in B, but I don't want to do it. Using any keywords in B is impossible for me either!

2

There are 2 answers

0
Valentin T. On BEST ANSWER

I just found the solution. Thanks for answers. I just need to change this line:

s._method( s); //ERROR, because _method is protected

to

( ( A< Self> &) s)._method( s);

And it works! http://ideone.com/CjclqZ

0
Ali Kazmi On
template< typename Self>
  class A {
  public:
      void foo( ) {
          Self s;
          s._method( s); //ERROR, because _method is protected
      }

  protected:
      virtual  void _method( const Self & b) = 0;
  };
  template< typename Self>
class B : public A< Self> {
protected:
    void _method( const Self & b) {}
};

Do it this way; In your Class A _method is pure virtual and you have to override it in Class B.