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

Accessing protected members of derived class with CRTP

本文关键字:受保护 成员 派生 CRTP 访问 使用      更新时间:2023-10-16

>我正在使用CRTP,并且在访问派生类的受保护成员时遇到问题。

这是示例,接近我的代码:

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) {}
};

明白了,我必须使用朋友关键字。但我不明白把它放在A类<自我>的什么地方。我知道我可以在 B 中公开 void _method( const B &B),但我不想这样做。B 中使用任何关键字对我来说也是不可能的!

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

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

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

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

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类中覆盖它。