150. Basic Lambda Callback

#include <iostream>
#include <string>
#include <functional>

class Button {
private:
    std::function<void()> onClick;

public:
    void setCallback(std::function<void()> cb) {
        onClick = cb;
    }

    void press() {
        if (onClick) {
            onClick();
        }
    }
};

int main() {
    Button btn;

    btn.setCallback([]() {
        std::cout << "Action Executed!" << std::endl;
    });

    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;

        if (cmd == "PRESS") {
            btn.press();
        }
    }
    return 0;
}

Explanation & Logic Summary

  • Lambda Expression: Defines behavior inline without creating a separate function.
  • std::function: Provides a generic way to store and invoke any callable object.
  • Decoupling: The Button class triggers the event, while main defines the response.

Firmware Relevance & Real-World Context

  • ISR Deferral: Lambdas can be queued for deferred execution outside interrupt context.
  • Embedded GUI Systems: Button widgets rely on callback-based designs.
  • Code Hygiene: Lambdas reduce global function clutter and improve locality of logic.

 

 

 

Loading...

Input

2 PRESS IDLE

Expected Output

Action Executed!