【发布时间】: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