1

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!

4

2 回答 2

2

我刚刚找到了解决方案。感谢您的回答。我只需要改变这一行:

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

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

它有效!http://ideone.com/CjclqZ

于 2014-11-19T17:37:35.547 回答
-1
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) {}
};

这样做;在您的 A 类中,_method 是纯虚拟的,您必须在 B 类中覆盖它。

于 2014-11-19T17:20:35.420 回答