As @chris commented, you can create a character map for functors:
std::map<char, std::function<double(double,double)> operators{ { '+', std::plus<double>{} }, { '-', std::minus<double>{} }, { '*', std::multiplies<double>{} }, { '/', std::divides<double>{} } }; double apply(double lhs, double rhs, char op) { return operators[op](lhs, rhs); }
This will call std::bad_function_call if you call the function with a character that is not a known statement.
It will also create unwanted map entries for such unknown characters in order to avoid minor glitches:
double apply(double lhs, double rhs, char op) { auto iter = operators.find(op); if (iter == operators.end()) throw std::bad_function_call(); return (*iter)(lhs, rhs); }
(NB This takes advantage of C ++ 11, but it can be easily translated to C ++ 03 using boost::function or std::tr1::function )
source share