Storing basic arithmetic operators in variables

How can I store the basic arithmetic operator in a variable?

I would 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 consider just +, -, *and /I could keep the operator stringand simply use a switch statement. However, I am wondering if there is a better / simpler way.

+5
source share
1 answer
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<>on std::minus<>, std::multiplies<>, std::divides<>and so on, if necessary. All of them are located in the header functional, so be sure #include <functional>.

Replace std::function<> boost::function<>if you are not using a recent compiler.

+10

All Articles