gpt4 book ai didi

c++11 - C++ CRTP : How to make only one (some) function of the base class as a friend to to the derived class?

转载 作者:行者123 更新时间:2023-12-02 02:48:32 24 4
gpt4 key购买 nike

我只想做 Base<DerivedImpl>::fct1()可以访问类(class) 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!
};

关于c++11 - C++ CRTP : How to make only one (some) function of the base class as a friend to to the derived class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com