2

Suppose I have a global function pointer like so:

void (*Callback)(My_special_t*);

If I want to assign it a lambda I do so like so:

Callback = [](My_special_t* instance) { 
   //Useful stuff
};

What I really would like to do is something like this:

Callback = [](My_special_t* instance) { 
   //Useful stuff
   Callback = /* Somehow get the current lambda? */
};

So my question is this:

Is it possible to reference the a lambda object from inside of itself.....and if so how?

DarthRubik
  • 3,927
  • 1
  • 18
  • 54

2 Answers2

1

I know lambda is very cool feature and because its coolness it is overused. Trying forcing lambda here is creating a problem.

Just define a function and problem is resolved.

void myNiceFunction(My_special_t *instance) {
    instance->doStuff();

    … … …

    if (instance->next) {
        myNiceFunction(instance->next);
    }
}

It is better since it is self documenting (if good name is provided) and it is testable (test can reach this function directly).

Marek R
  • 32,568
  • 6
  • 55
  • 140
0

You can do it with std::function, like this:

#include <functional>
#include <iostream>

using std::cout;
using std::function;

struct My_special_t
{
};

int main()
{
  function<void(My_special_t*)> Callback;

  auto otherCallback = [](My_special_t* instance)
  {
    cout << "otherCallback " << static_cast<void*>(instance) << "\n";
  };

  Callback = [&Callback, &otherCallback](My_special_t* instance)
  {
    cout << "first callback " << static_cast<void*>(instance) << "\n";
    Callback = otherCallback;
  };

  My_special_t special;
  Callback(&special);
  Callback(&special);
}
Eljay
  • 4,648
  • 3
  • 16
  • 27
  • I can't use `std::function` because I need it to be a function pointer (it is using a c api) – DarthRubik Apr 14 '18 at 16:48
  • @DarthRubik • a lambda won't work either, then. A lambda creates an object, it does not create something that is compatible with or used as a function pointer. – Eljay Apr 14 '18 at 17:26
  • 1
    @Eljay That's [not quite true](https://stackoverflow.com/questions/28746744/passing-lambda-as-function-pointer) in the case of a non-capturing `lambda`. – G.M. Apr 14 '18 at 17:59