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.
int a = 1;
int b = 2;
std::function<int(int, int)> op = std::plus<int>();
int c = op(a, b);
if (c == 3) // do something
Replace std::plus<>
with std::minus<>
, std::multiplies<>
, std::divides<>
, etc., as need be. All of these are located in the header functional
, so be sure to #include <functional>
beforehand.
Replace std::function<>
with boost::function<>
if you're not using a recent compiler.