Reputation: 1267
I have defined the macro as follows
#define COMPARE(OPERATOR, FUNCTION) \
template <typename T> \
void FUNCTION(T *compArrayA, T *compArrayB, bool *resArray, int size) { \
for (int idx = 0; idx <= size; ++idx ) { \
resArray[idx] = (compArrayA[idx] OPERATOR compArrayB[idx]); \
} \
} \
COMPARE(==, eq);
COMPARE(!=, nq);
COMPARE(>=, greater_eq);
So, I tried to call the function defined in the macro as follows.
float *ArrayA, *ArrayB;
bool *ArrayRes;
ArrayA = (float *) malloc(sizeof(float)* 100);
ArrayB = (float *) malloc(sizeof(float)* 100);
ArrayRes = (bool *) malloc(sizeof(bool) * 100);
eq(ArrayA, ArrayB, ArrayRes, 100);
I received the following error.
eq.h(11): error: expected an expression
1 error detected in the compilation of "eq.cpp".
eq.h(11) represents the following line.
COMPARE(==, eq);
How do I define a function in a macro?
I just want to know how to implement functions using macros.
Upvotes: 0
Views: 120
Reputation: 2937
Short answer, don't do that. Since you've templates you can use standard library approach from functional header
without any macro definitions at all.
For example:
template<typename E, class Pred>
void vcompare(E *compArrayA, E *compArrayB, bool *resArray, int size) {
for (int idx = 0; idx <= size; ++idx ) {
resArray[idx] = Pred(compArrayA[idx], compArrayB[idx]);
}
}
vcompare<int,std::less>(lhs,rhs,res,len);
vcompare<int,std::greater>(lhs,rhs,res,len);
P.S. Check std::vector class and general STL part inside standard C++ library.
Upvotes: 2
Reputation: 21
What you are trying to do is to pass operator as an argument.
Passing an operator as an argument to a function in C
As Victor Gubin already answered it is best to avoid macro and embrace modern alternatives to do the same you are trying to achieve.
Upvotes: 0
Reputation: 218268
As you define your MACRO, you shouldn't use ;
after it, so
COMPARE(==, eq)
COMPARE(!=, nq)
COMPARE(>=, greater_eq)
instead of
COMPARE(==, eq);
COMPARE(!=, nq);
COMPARE(>=, greater_eq);
Upvotes: 1