How can I store a basic arithmetic operator in a variable?
I’d like to do something like this in c++:
int a = 1;
int b = 2;
operator op = +;
int c = a op b;
if (c == 3) // do something
Since I’m considering only +, -, * and / I could store the operator in a string and just use a switch statement. However I’m wondering if there’s a better/easier way.
Replace
std::plus<>withstd::minus<>,std::multiplies<>,std::divides<>, etc., as need be. All of these are located in the headerfunctional, so be sure to#include <functional>beforehand.Replace
std::function<>withboost::function<>if you’re not using a recent compiler.