【问题标题】:C++ CRTP: How to make only one (some) function of the base class as a friend to to the derived class?C ++ CRTP:如何使基类的一个(某些)函数成为派生类的朋友?
【发布时间】:2018-11-09 17:00:58
【问题描述】:

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

【问题讨论】:

  • 如果你将Base::fct1() 设为public 成员函数,你会很高兴的。
  • @RSahu 谢谢!然而,这迫使我的基类使其成员公开......
  • 无论这是否适合您的用例,您都必须进行调用。

标签: c++11 crtp friend-function


【解决方案1】:

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

您可以通过滥用允许派生类访问其父类的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!
};

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2018-08-23
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多