I'm using a function of an external library written in C (library_function
) that takes a callback function as an argument. The parameters the library calls the callback function with don't matter to me. The only thing I'm interested in is the order of the calls to the callback function. I want the callback function to return the next element of a list every time it's called.
Consider this example:
#include <iostream>
int x;
bool *booleans;
void library_function(bool(*callback_fn)()){
for (int i=0; i < 5; i++) {
std::cout << callback_fn() << std::endl;
}
}
bool my_callback_fn(){
return booleans[x++];
}
void my_function(bool b[]){
x = 0;
booleans = b;
library_function(my_callback_fn);
}
int main() {
bool booleans[] {true, false, true, true, false};
my_function(booleans);
}
This code works, but I had to use global variables which I think isn't good style.
In Python for example, I would use an inner function to achieve this:
def library_function(callback_fn):
for _ in range(5):
print(callback_fn())
def my_function(b):
x = -1
def my_callback_fn():
nonlocal x
x += 1
return b[x]
library_function(my_callback_fn)
if __name__ == '__main__':
booleans = [True, False, True, True, False]
my_function(booleans)
I've read that C++ doesn't support nested functions and that lambda functions can only be used as function pointers if they do not capture variables.
Is there a way to avoid using global variables but still being able to modify the 'internal state' of the callback function?