Lambda functions work pretty well for this. To use them, #include <functional>
at the top of your code. When you have a function that takes in a function, you’d use syntax like this:
#include <functional>
//Callback return type outside, parameter types inside the parentheses.
void iCallYourFunction(std::function<void(int, int, int)> func) {
func(1, 2, 3);
}
In code calling this function, a lambda is used (or a regular function of course).
void multiplier(int a, int b, int c) {
printf("Callback values multiplied were: %d\n", a * b * c);
}
int main(int argc, char** argv) {
iCallYourFunction([&](int a, int b, int c) {
printf("I got values %d, %d, %d passed into this callback.\n", a, b, c);
});
iCallYourFunction(multiplier);
}
Note the [&] which allows variables outside the lambda to be used inside of it. & means that values outside the lambda will be referenced. If they are changed by the time the lambda runs, the lambda will use the changed value. See below for an example:
#include <vector>
int main(int argc, char** argv) {
//List (vector) of functions (std::function)
std::vector<std::function<void(int, int, int)>> callbacks;
//Add callbacks for each number from 0 to 9.
for(int i = 0; i < 10; i++) {
callbacks.push_back([&](int a, int b, int c) {
printf("Value of i inside here is %d.\n", i);
});
}
//For each callback, call it with iCallYourFunction
for(int i = 0; i < callbacks.size(); i++) {
iCallYourFunction(callbacks[i]);
}
}
Fun fact: Both C++ and JS both have the same behavior here! You’ll get “10” printed 10 times.
In C++ however, you can make a copy of the value each time the lambda is created. To do this, simply replace [&] with [=] in the example above.
In JS, you can create a new variable each time by changing the loop variable to let i
instead of var i
.
You can choose some variables to copy and some to reference with [&, =copyThis, =copyThat]
.
The last kind of capture specifier as they’re called is []. This will disallow using any outside variables, but allow the lambda to act like a regular C-style function pointer, which is great for working with functional C libraries and creating pros::Task
s.
Hopefully this clears up how lambdas work for you!