I want to do something like this:
int a = 9, b = 3;
map<char,operator> m;
m['+'] = +;
m['-'] = -;
m['*'] = *;
m['/'] = /;
for(map<char,operator>::iterator it = m.begin(); it != m.end(); ++it) {
cout << func(a,b,it -> second) << endl;
}
With the output being something like this:
12
6
27
3
How can I do it?
You can use the premade functors in
<functional>:Each one is a class with an
operator()that takes two arguments and returns the result of a mathematical operation on those two arguments. For example,std::plus<int>()(3, 4)is basically the same as3 + 4. Each is stored as a function wrapper object of the signatureint(int, int)and then called with the two numbers as needed.