Search code examples
c++c++11std-function

Creating a closure for std::function


I am not sure if I am using the exact terminology , But I'll try to be as descriptive as possible to clear out any confusion .

Suppose I have an std::function variable

std::function<void(int)>  callback ;

Due to some reasons beyond my scope , I cannot change the function prototype. I receive the std::function variable at some point in my code and I have to call it.Something like this :

int a = 10 // just an example value
callback(a); 

Now I have another variable . Let's name it id .

int id = rand(); // Let us assume that rand here generates a random variable
int a = 10 // just an example value
callback(a);

I want id to be accessible inside the callback i.e I am looking for some form of closure . Is there any way to do it without making the id static/global.


Solution

  • No, you cannot do that.

    callback has no state unless it was designed to have state (which it wasn't).

    This shouldn't matter, though: if you have no control over the callback, then it already does not want to use your variable id. And if you do have control over it, then you can simply replace it with a lambda that does capture the variable and do whatever you want to do with it.