Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing basic arithmetic operators in variables

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.

like image 552
MrDatabase Avatar asked May 03 '12 02:05

MrDatabase


1 Answers

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.

like image 122
ildjarn Avatar answered Oct 11 '22 17:10

ildjarn