152. Class Method Callback

In C++, you cannot pass a non-static member function (like Motor::step) directly to a handler expecting a simple function pointer, because member functions require a specific object instance (this) to operate.

Your task is to use a Lambda to "glue" a generic driver to a specific object instance.

  1. Implement class Driver:
    • Member: std::function<void()> callback.
    • Method: void execute() calls the callback if valid.
    • Method: void setCallback(std::function<void()> cb).
  2. Implement class Motor:
    • Member: int position (Initialize to 0).
    • Method: void step(): Increments position and prints Position: <new_pos>.
  3. In main:
    • Instantiate Driver and Motor.
    • Register a lambda with the driver that captures the motor instance by reference and calls its step() method.

Program Flow:

  1. Instantiate Driver and Motor.
  2. Bind the motor's step function to the driver using a lambda.
  3. Read integer N.
  4. Loop N times.
  5. Read string cmd.
  6. If cmd is "TRIG", call driver.execute().

Input Format:

  • First line: Integer N.
  • Next N lines: String cmd ("TRIG" or other).
  • Input is provided via standard input (stdin).

Output Format:

  • For each "TRIG": Position: <value>
  • Each output must be on a new line.

Example: 

Example 1

Input:

2
TRIG
TRIG

Output:

Position: 1
Position: 2

Constraints:

  • Must use std::function in the Driver.
  • Must use a lambda in main.
  • Must capture motor by reference ([&]) in the lambda.

 

 

 

 

Loading...

Input

2 TRIG TRIG

Expected Output

Position: 1 Position: 2