151. Stateful Lambda Counter

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

class Ticker {
private:
    std::function<void()> callback;

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

    void tick() {
        if (callback) callback();
    }
};

int main() {
    Ticker sys_tick;

    sys_tick.setCallback([count = 0]() mutable {
        ++count;
        std::cout << "Count: " << count << 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 == "TICK") {
            sys_tick.tick();
        }
    }
    return 0;
}

Explanation & Logic Summary:

  • Capture Initialization:
    [count = 0] creates a member variable inside the lambda object, initialized once when the lambda is created.
  • Mutable Lambda:
    By default, value-captured variables are const. The mutable keyword allows modification of the lambda’s internal state.
  • State Persistence:
    The lambda is stored inside std::function within Ticker, so its internal count persists across calls to tick().

Firmware Relevance & Real-World Context:

  • Software Timers: Counting timer expirations without global state
  • Retry Counters: Tracking packet resend attempts in communication stacks
  • Encapsulation: Keeps callback-specific state local, testable, and reusable
  • Interrupt-Safe Design Pattern: Avoids hidden static state and namespace pollution

 

 

 

Loading...

Input

3 TICK WAIT TICK

Expected Output

Count: 1 Count: 2