Re: How do I put a pointer to an operator?
leriaat@elte.hu wrote:
I would like to create a calculator, and I thought that it would be a
good idea to write a universal "do_it" function that would have a
pointer to the operator and the two operands like this:
double do_it(double a, doulbe b, doulbe (*op)(doulbe, doulbe) ) {
return op(a, b); }
Well, the idea is great, but I don't know how could I put a pointer to
the + operator... Is it possible at all? I mean something like this:
cout << do_it(1, 2, &(operator+) );
You can't get pointers to the built-in operators. You can write functions
that themselves use those operators and then get pointers to those
functions. But I think it would be better to make an abstract Operator base
class and for each operation that your calculator can do add a class that
derives from it. Something like:
#include <iostream>
class Operator
{
public:
virtual double operator()(double a, double b) const = 0;
virtual const char* name() const = 0;
};
class Plus : public Operator
{
double operator()(double a, double b) const
{
return a + b;
}
const char* name() const { return "+"; }
};
class Minus : public Operator
{
double operator()(double a, double b) const
{
return a - b;
}
const char* name() const
{
return "-";
}
};
void calc_result(double a, double b, const Operator& op)
{
std::cout << a << ' ' << op.name()
<< ' ' << b << " = "
<< op(a, b) << '\n';
}
int main()
{
double a = 7, b = 6;
calc_result(a, b, Plus());
calc_result(a, b, Minus());
}