musako
musako

Reputation: 1267

How to define multiple operators using macros

I'm going to use a single macro to set the ==, ! =, >, >=, etc. for an array in one macro.

#define COMPARE(operator, function)                                         \ 
    template <typename T>                                                   \
    void function(T *compArrayA, T *compArrayB, bool *resArray, int size) { \
        for (int i = 0; i <= size; ++i ) {                                  \
            resArray[idx] = (compArrayA[idx] ## operator compArrayB[idx]);  \
        }                                                                   \
    }                                                                       \

COMPARE(==, eq);
COMPARE(!=, nq);
COMPARE(>=, greater_eq);

I wrote the code as above. This code gave me the following error.

error: "#" not expected here

How can I modify it to define different operators using macros?

Upvotes: 1

Views: 233

Answers (1)

iammilind
iammilind

Reputation: 70040

operator is a C++ keyword. Avoid using it to avoid compilation issues. Standard practice is to use full caps for all the macro arguments; e.g.

#define COMPARE(OPERATOR, FUNCTION) \ ...

Moreover, here the ## part is unwanted, since there is no string concatenation happening in your code. Simply use OPERATOR argument as it is.

Upvotes: 2

Related Questions