In my .h
file, I have a class like this:
#pragma once
class Widget {
int private_data;
friend void foo(Widget& w);
}
As I was implementing foo
, it turns out I need a helper function:
static void foohelper(Widget& w) {
printf("further processing %d", w.private_data);
}
void foo(Widget& w) {
printf("processing %d", w.private_data);
foohelper(w);
}
I don't want to put foohelper
in the .h
file, because it is an implementation detail, but that means there's no way for it to become a friend
directly.
In this example, one could get away with just passing the private_data
directly, but in a real use case, this doesn't scale well when Widget
has more private variables.
I only ever call foohelper
from foo
, so if c++ supported nested function definitions, I wouldn't have a problem:
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);
}
But, c++ doesn't allow this as a solution.
Is it possible for a function to pass friend
status to a helper function?
C++ doesn't have inner function, but you can use lambda for that:
void foo(Widget& w) {
auto foohelper = [](Widget& w) {
printf("further processing %d", w.private_data);
};
printf("processing %d", w.private_data);
foohelper(w);
}