1

Say I have a wrapper function that goes around some smaller recursive function. However, the wrapper, before calling the recursive function creates an object which the recursive function uses. How can I do this in c++? Do I just need to make it its own class? EDIT - I know if I can make it into a class and how to take it from there - but my question is do I need a class or can I somehow getaway without making one?

I made a generic example to clarify my question:

void wrapper()
{
    Object myObject;
    bool recurFun(int x)
    {
        // do some stuff with myObject
        if (some condition){return recurFun(x-1)}
        else {return true}
    }
}

Please ignore any basic syntax type errors, it is not a working example simply one to help get my question across to you guys. Thanks!

Joker
  • 2,119
  • 4
  • 27
  • 38

2 Answers2

14

You can use lambdas to get closures:

void wrapper()
{
    Object myObject;
    std::function<bool(int)> recurFun;
    recurFun = [&](int x) -> bool {
        // do some stuff with myObject
        if (some condition){return recurFun(x-1)}
        else {return true}
    }
}
Pubby
  • 51,882
  • 13
  • 139
  • 180
2

The first thing that should come to your mind when a function needs to use something is to make it a parameter of that function. So have your recursive function accept the object as a parameter and thread it around in the recursive calls. The wrapper function will do the natural thing of setting up the object and passing it.

Luc Danton
  • 34,649
  • 6
  • 70
  • 114