153. Configurable Math Engine

#include <iostream>
#include <string>

// 'MathOp' is now an alias for "int (*)(int, int)"
// This makes the rest of the code much easier to read.
typedef int (*MathOp)(int, int); 

int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

class Calculator {
private:
    MathOp current_op = add; // Initialize with a default function

public:
    void setMode(MathOp op) {
        current_op = op;
    }

    void compute(int a, int b) {
        // We use the pointer just like a regular function name
        int res = current_op(a, b);
        std::cout << "Result: " << res << std::endl;
    }
};

int main() {
    Calculator calc;
    int N;
    if (!(std::cin >> N)) return 0;

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

        if (cmd == "MODE_ADD") {
            calc.setMode(add);
        } else if (cmd == "MODE_MUL") {
            calc.setMode(multiply);
        } else if (cmd == "CALC") {
            int a, b;
            std::cin >> a >> b;
            calc.compute(a, b);
        }
    }
    return 0;
}

Explanation & Logic Summary:

  • The Typedef: typedef int (*MathOp)(int, int); tells the compiler that whenever we write MathOp, we mean "a pointer to a function taking two ints and returning an int".
  • Flexibility: The Calculator class is agnostic. It doesn't know how to compute, it just knows it has a function that can compute. This allows us to inject new behavior (like subtract or divide) later without changing the class code.

Firmware Relevance & Real-World Context:

  • Hardware Abstraction Layer (HAL): You might define typedef void (*WritePinFn)(bool state);. The upper layer logic simply calls writePin(true), regardless of whether that function toggles a GPIO, sends an I2C command, or writes to a shift register.
  • Algorithm Swapping: An audio device might switch from a "High Quality" filter function to a "Low Power" filter function when the battery drops below 10%, simply by updating one function pointer.

 

 

 

 

Loading...

Input

3 CALC 10 10 MODE_MUL CALC 10 10

Expected Output

Result: 20 Result: 100