fork 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 (*FuncType)(double, double);
  10.  
  11. static unordered_map<string, FuncType> operator_function;
  12.  
  13. static double multiply(double num_1, double num_2) {
  14. cout << "MULTIPLYING!" << endl;
  15. return num_1 * num_2;
  16. }
  17.  
  18. static double exponent(double num_1, double num_2) {
  19. cout << "EXPONENT!" << endl;
  20. return pow(num_1, num_2);
  21. }
  22.  
  23. public:
  24. static double do_math(string op, double num_1, double num_2) {
  25. FuncType func = operator_function[op];
  26. return func(num_1, num_2);
  27. }
  28. };
  29.  
  30. unordered_map<string, Calculator::FuncType> Calculator::operator_function = {
  31. {"*", &Calculator::multiply},
  32. {"^", &Calculator::exponent},
  33. {"**", &Calculator::exponent}
  34. // and so on ...
  35. };
  36.  
  37. int main() {
  38. cout << Calculator::do_math("*", 123, 45) << endl;
  39. cout << Calculator::do_math("^", 123, 2) << endl;
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5504KB
stdin
Standard input is empty
stdout
MULTIPLYING!
5535
EXPONENT!
15129