Programs & Examples
Lambda Expressions · Study material
An event bus with lambda handlers
Handlers are lambdas stored in std::function objects. Each captures the variable it updates by reference – safe here because all of them live in main as long as the bus does.
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <vector>
class EventBus {
std::map<std::string, std::vector<std::function<void(const std::string&)>>> handlers_;
public:
void on(const std::string& event, std::function<void(const std::string&)> f) { handlers_[event].push_back(std::move(f)); }
void emit(const std::string& event, const std::string& data) {
for (auto& f : handlers_[event]) f(data);
}
};
int main() {
EventBus bus;
int orders = 0;
double revenue = 0;
std::vector<std::string> log;
bus.on("order", [&orders](const std::string&) { ++orders; });
bus.on("order", [&revenue](const std::string& amount) { revenue += std::stod(amount); });
bus.on("order", [&log](const std::string& amount) { log.push_back("order of " + amount); });
bus.on("refund", [&revenue](const std::string& amount) { revenue -= std::stod(amount); });
bus.emit("order", "499.50");
bus.emit("order", "1200");
bus.emit("refund", "499.50");
std::cout << orders << " orders, revenue " << revenue << ", last: " << log.back() << '\n';
return 0;
}
2 orders, revenue 1200, last: order of 1200
Counters and ID generators with mutable lambdas
The mutable example shows how by-value captures act as private state that persists between calls, and how copying a lambda copies that state.
Recursive Fibonacci with deducing this
The recursion example compares C++23 deducing this, std::function and the "pass yourself" technique.