Ad
Code
Diff
  • #include <functional>
    #include <string>
    #include <array>
    using namespace std;
    
    template <typename T>
    string calculator(int op, T x, T y) {
      static array<std::function<T(T, T)>,5> ops{
        plus<>{},minus<>{},multiplies<>{},divides<>{},modulus<>{},
      };
      static array<std::function<string()>, 2> func{
        [&]() {return to_string(ops[op-1](x, y));},
        [&]() {return "Invalid Input!";},
      };
    
      return (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) ? func[1]() : func[0]();
    }
    
    • #include <functional>
    • #include <string>
    • #include <array>
    • using namespace std;
    • template <typename T>
    • string calculator(int op, T x, T y) {
    • static array<std::function<T(T, T)>,5> ops{
    • plus<>{},minus<>{},multiplies<>{},divides<>{},modulus<>{},
    • };
    • static array<std::function<std::string()>, 2> func{
    • [&]() {return std::to_string(ops[op-1](x, y));},
    • static array<std::function<string()>, 2> func{
    • [&]() {return to_string(ops[op-1](x, y));},
    • [&]() {return "Invalid Input!";},
    • };
    • return func[op < 1 || op > 5 || (!y && (op == 4 || op == 5))]();
    • }
    • return (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) ? func[1]() : func[0]();
    • }