c++11 - 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();
}
解决方案
免责声明:这回答了所提出的问题,但在我看来,不同的设计方法可能更可取,所以我不建议你在生产中这样做,除非你绝对必须这样做。
您可以通过滥用派生类允许访问其父类的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!
};
推荐阅读
- excel - VBA 程序未在 View Macros 上“显示”
- swift - 我不理解此类中的参数(Swift)
- mysql - 按周和周分组从星期二开始
- javascript - 使用 javascript 和 php 循环 Div
- python - Pandas:根据索引列中的条件填充和合并两个不同的数据框
- java - Integer.toBinaryString() 未正确转换为二进制
- google-cloud-platform - 如何在 Cloud Composer 环境中安装 jq
- python - 获取函数或源代码中调用的所有函数
- reactjs - 尽管使用了 withRouter,为什么 this.props.history 未定义?
- spring-boot - 分布式系统中不同类型的事件——拆分或合并