Lambdas and Callables
Function Callbacks
std::function can store a callable and pass it to another function.
Function Callbacks
function_callbacks.cpp
#include <functional>
#include <iostream>
void repeat(int count, const std::function<void(int)>& callback) {
for (int index = 1; index <= count; index++) {
callback(index);
}
}
int main() {
int count = ;
int total = 0;
repeat(count, [&total](int index) {
total += index;
});
std::cout << "total=" << total << std::endl;
std::cout << "done=" << count << std::endl;
return 0;
}
#include <functional>
#include <iostream>
void repeat(int count, const std::function<void(int)>& callback) {
for (int index = 1; index <= count; index++) {
callback(index);
}
}
int main() {
int count = ;
int total = 0;
repeat(count, [&total](int index) {
total += index;
});
std::cout << "total=" << total << std::endl;
std::cout << "done=" << count << std::endl;
return 0;
}
#include <functional>
#include <iostream>
void repeat(int count, const std::function<void(int)>& callback) {
for (int index = 1; index <= count; index++) {
callback(index);
}
}
int main() {
int count = ;
int total = 0;
repeat(count, [&total](int index) {
total += index;
});
std::cout << "total=" << total << std::endl;
std::cout << "done=" << count << std::endl;
return 0;
}
callback
A callback is a callable passed to another function so that function can call it later.