朋友功能需要助手功能

干粉

在我的.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状态传递给助手函数?

贾罗德42

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章