【问题标题】:Accessing protected members of derived class with CRTP使用 CRTP 访问派生类的受保护成员
【发布时间】:2015-01-17 07:47:51
【问题描述】:

我正在使用 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) {}
};

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

【问题讨论】:

  • friend class A&lt;B&gt;; 放入B
  • 在 B 中使用任何关键字对我来说都是不可能的。
  • 这是为什么呢?它在这里工作——coliru.stacked-crooked.com/a/954e7d10d6e1de89
  • 在我的代码中,我可能不知道所有可能的推导。而且我不能命令从这个类中派生它的人给朋友。

标签: c++ friend crtp friend-function


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:
    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 类中覆盖它。

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2018-04-17
      • 2015-12-30
      相关资源
      最近更新 更多