fork(2) download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4. #include <cmath>
  5. using namespace std;
  6.  
  7. class Calculator {
  8. private:
  9. typedef double (Calculator::*FuncType)(double, double);
  10.  
  11. unordered_map<string, FuncType> operator_function = {
  12. {"*", &Calculator::multiply},
  13. {"^", &Calculator::exponent},
  14. {"**", &Calculator::exponent}
  15. // and so on ...
  16. };
  17.  
  18. double multiply(double num_1, double num_2) {
  19. cout << "MULTIPLYING!" << endl;
  20. return num_1 * num_2;
  21. }
  22.  
  23. double exponent(double num_1, double num_2) {
  24. cout << "EXPONENT!" << endl;
  25. return pow(num_1, num_2);
  26. }
  27.  
  28. public:
  29. double do_math(string op, double num_1, double num_2) {
  30. FuncType func = operator_function[op];
  31. return (this->*func)(num_1, num_2);
  32. }
  33. };
  34.  
  35. int main() {
  36. Calculator calc;
  37. cout << calc.do_math("*", 123, 45) << endl;
  38. cout << calc.do_math("^", 123, 2) << endl;
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5492KB
stdin
Standard input is empty
stdout
MULTIPLYING!
5535
EXPONENT!
15129