在我的.h
文件中,我有一个像这样的类:
#pragma once
class Widget {
int private_data;
friend void foo(Widget& w);
}
在实现时foo
,事实证明我需要一个辅助函数:
static void foohelper(Widget& w) {
printf("further processing %d", w.private_data);
}
void foo(Widget& w) {
printf("processing %d", w.private_data);
foohelper(w);
}
我不希望把foohelper
中.h
的文件,因为它是一个实现细节,但是这意味着没有办法使它成为一个friend
直接。
在此示例中,仅通过private_data
直接传递就可以逃脱,但是在实际用例中,当Widget
拥有更多的私有变量时,这种方法无法很好地扩展。
我只会foohelper
从调用foo
,因此,如果c ++支持嵌套函数定义,则不会有问题:
void foo(Widget& w) {
void foohelper(Widget& w) { // compiler: function definition is not allowed here
printf("further processing %d", w.private_data);
}
printf("processing %d", w.private_data);
foohelper(w);
}
但是,c ++不允许将此作为解决方案。
函数是否可以将friend
状态传递给助手函数?
C ++没有内部函数,但是您可以为此使用lambda:
void foo(Widget& w) {
auto foohelper = [](Widget& w) {
printf("further processing %d", w.private_data);
};
printf("processing %d", w.private_data);
foohelper(w);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句