C ++ CRTP:如何仅使基类的一个(某些)功能作为派生类的朋友?

时间:2018-11-09 17:00:59

标签: c++11 crtp friend-function

我只想让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();
}

1 个答案:

答案 0 :(得分:1)

免责声明:这样可以回答所问的问题,但我认为,可能更希望采用其他设计方法,因此,除非绝对必要,否则我建议您不要在生产中进行此操作。 / p>

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

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