Is there an EASY way to simulate local functions?

81 Views Asked by At

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; }
    }
};
1

There are 1 best solutions below

2
Mooing Duck On

Just put them in a struct

struct S final
{
   struct g_params { //that's it
      double d;
   };

   int i = 123;
   void f()
   {
      g_params d = {1.23};
      g(d);
      // ... assume this is already a large function ...
   }
   // ... lots of code here ...
   void g(g_params& p)
   {
      i = 456; p.d = 4.56;
   }
};