1
votes

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
Put friend class A<B>; in B.0x499602D2
Using any keywords in B is impossible for me.Valentin T.
Why is that? It works here -- coliru.stacked-crooked.com/a/954e7d10d6e1de890x499602D2
In my code I may not know all the possible derivations. And I can't order people who derives it to friend from this class.Valentin T.

2 Answers

2
votes

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

-1
votes
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.