Originally Posted by
DawnOfMe
what I would like to do would be answer = (a b c)
where a is some number b is an operator (such as +) and c is another number
You can use function pointers for this. (a b c) is the same as saying b(a,c), where b is a function that performs arithmetic such as adding two numbers. For example, define these two functions:
Code:
int op_plus(int a, int b)
{
return a+b;
}
int op_minus(int a, int b)
{
return a-b;
}
Now the appropriate function can be placed in a function pointer at runtime:
Code:
int main()
{
int a = 100;
int c = 200;
cout << "Enter + or -: ";
char q;
cin >> q;
typedef int (*FT)(int,int);
FT b = nullptr;
switch(q) {
case '+': b = static_cast<FT>(op_plus);
break;
case '-': b = static_cast<FT>(op_minus);
break;
}
if (b) {
cout << "answer = " << b(a,c) << endl;
}
}
There are many ways to map your operator input parameter '+', '-', etc into operations. And you'll probably extend and change it as development goes on, so it might be a good idea to move the function pointer stuff into a class:
Code:
struct Operation {
typedef int (*FT)(int,int);
FT b = nullptr;
Operation(char q)
{
switch(q) {
case '+': b = static_cast<FT>(op_plus);
break;
case '-': b = static_cast<FT>(op_minus);
break;
}
}
int operator()(int a, int c) const { return b(a,c); }
operator int() const { return (int)b; }
};
Now the main code becomes:
Code:
#include <iostream>
using namespace std;
/* ... declarations here */
int main()
{
int a = 100;
int c = 200;
cout << "Enter + or -: ";
char q;
cin >> q;
Operation b(q);
if (b) {
cout << "answer = " << b(a,c) << endl;
}
}