I've got a member-function that need to access both member data and "local" data:
struct S final
{
int i = 123;
// ... a bunch of legacy code ...
void f()
{
// ... a bunch of legacy code ...
double d = 1.23;
// ... a bunch of legacy code ...
g(d);
// ... a bunch of legacy code ...
}
// ... a bunch of legacy code ...
void g(double& d)
{
i = 456; d = 4.56;
}
};
This, of course, works ... however, it becomes a nuisance as more variables local to f()
are passed to g()
. Is there an 'easy' way to avoid this?
Using a lambda is the "stock" answer, however that means the code for g()
must be moved to be part of f()
; I don't want to do that:
struct S final
{
int i = 123;
void f()
{
double d = 1.23;
auto g = [&]() { i = 456; d = 4.56; } // code moved here :-(
g(d);
}
};
Something like this is close (although the lambda is "better" as local variables are part of the closure with [&]
), but it's not valid C++
struct S final
{
int i = 123;
void f()
{
double d = 1.23;
void g();
g();
}
void f::g()
{
i = 456; d = 4.56;
}
};
Or (again, using fictional syntax) a way to declare a lambda and then define it later:
struct S final
{
int i = 123;
void f()
{
double d = 1.23;
auto g = [&]();
g();
g = { i = 456; d = 4.56; }
}
};