#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:
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".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:
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.
Input
3 CALC 10 10 MODE_MUL CALC 10 10
Expected Output
Result: 20 Result: 100