首页 > 解决方案 > C ++ CRTP:如何使基类的一个(某些)函数成为派生类的朋友?

问题描述

我想只Base<DerivedImpl>::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!!
};

主要c++:

int main(){
DerivedImpl obj;
obj.callbase();
}

标签: c++11crtpfriend-function

解决方案


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

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

#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!
};

推荐阅读