C++11 C++;CRTP:如何使基类的一个(部分)函数成为派生类的朋友?

C++11 C++;CRTP:如何使基类的一个(部分)函数成为派生类的朋友?,c++11,crtp,friend-function,C++11,Crtp,Friend Function,我只想使Base::fct1()能够访问类DerivedImpl成员 基址看起来像: template < typename Derived> class Base<Derived>{ protected: void fct1(){ static_cast<Derived*>(this)->topfunc(); } void fct2(){ ... } }; class DerivedImpl: public Base<DerivedImp

我只想使
Base::fct1()
能够访问类
DerivedImpl
成员

基址看起来像:

template < typename Derived>
class Base<Derived>{

protected:
void fct1(){
static_cast<Derived*>(this)->topfunc();
}

void fct2(){
...
}

};
class DerivedImpl: public Base<DerivedImpl>{

void callbase(){fct1();}
void topfunc(){std::cout << "topfunc" <<std::endl;}

friend Base<DerivedImpl>; //this works
//friend void Base<DerivedImpl>::fct1(); //does not work!!
};

免责声明:这回答了所问的问题,但在我看来,不同的设计方法可能更可取,因此我不建议您在生产中这样做,除非您必须这样做

您可以通过滥用允许派生类访问其父类的
受保护
静态成员这一事实来解决此问题:

#include <iostream>

template<typename Derived>
class Base {
protected:
  static void fct1(Base* self){
    static_cast<Derived*>(self)->topfunc();
  }

  void fct2() {}
};

class DerivedImpl: public Base<DerivedImpl> {

  void callbase() { fct1(this); }
  void topfunc() { std::cout << "topfunc" << std::endl; }

  friend void Base<DerivedImpl>::fct1(Base*); // works fine now!
};
#包括
模板
阶级基础{
受保护的:
静态空隙fct1(基础*自身){
静态_cast(self)->topfunc();
}
void fct2(){}
};
类DerivedImpl:公共基{
void callbase(){fct1(this);}

void topfunc(){std::cout如果您使用
Base::fct1()
a
public
成员函数,您就可以使用了。@RSahu谢谢!但是这会强制我的基类将其成员设为public…您必须进行调用,以确定这是否适合您的用例。
#include <iostream>

template<typename Derived>
class Base {
protected:
  static void fct1(Base* self){
    static_cast<Derived*>(self)->topfunc();
  }

  void fct2() {}
};

class DerivedImpl: public Base<DerivedImpl> {

  void callbase() { fct1(this); }
  void topfunc() { std::cout << "topfunc" << std::endl; }

  friend void Base<DerivedImpl>::fct1(Base*); // works fine now!
};