Dear Team, attempted to post the following question through the usual channels, but then got an "Attack" dialog, unfortunately.
Suppose there is a series of statements throughout our program like
//a,b,c,d integers
if (condA)
result = f(a) | g(b)
else
result = f(a) & ~g(b)
...
if (condB)
result = f(c) & ~g(d)
else
result = f(c) | g(d)
...
The ultimate goal is to use a ternary operator on the operators to reduce code:
condB? magicalOpVarConst = "~!": magicalOpVarConst = "|";
result = f(c) & TurnIntomagicalOpVarConst(magicalOpVarConst) & g(d)
This obviously won't compile, so try templates:
struct opOr
{
template <typename T, typename U>
bool operator()(T a, U b)
{
return a | b;
}
};
struct opAndNot
{
template <typename T, typename U>
bool operator()(T a, U b)
{
return a & ~b;
}
};
template <typename T, typename OP>
struct expression
{
T& a;
T& b;
OP& op;
expression
// Code Continuation Alert: Cannot place arguments directly after expression or the BBCode goes burko.
(T a, T b, OP op) : a(a), b(b), op(op) {}
int eval() { return op(a, b); }
};
And the caller:
if (condA)
expression<int, opAndNot> exp(f(a), g(b), opAndNot());
else
expression<int, opOr> exp(f(a), g(b), opOr());
int retVal = exp.eval();
This gets a C2228, understandable, it seems. Can anything be added to the template functions to make it work?
Thanks.