Class Method Callback

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

class Driver {
private:
    std::function<void()> callback;
public:
    void setCallback(std::function<void()> cb) {
        callback = cb;
    }
    void execute() {
        if (callback) callback();
    }
};

class Motor {
private:
    int position = 0;
public:
    void step() {
        position++;
        std::cout << "Position: " << position << std::endl;
    }
};

int main() {
    Driver driver;
    Motor motor;

    // TODO: Register a callback with 'driver'.
    // The callback must be a Lambda that calls 'motor.step()'.
    // Hint: Capture 'motor' by reference [&motor] or [&].
    
    auto cb = [&motor]() {
        motor.step();
    };
    driver.setCallback(cb);

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

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;
        if (cmd == "TRIG") {
            driver.execute();
        }
    }
    return 0;
}
Upvote
Downvote
Loading...

Input

2 TRIG TRIG

Expected Output

Position: 1 Position: 2