Subscribe to 10 GOTO 10        RSS Feed
-----

Macros & Operators

Icon 1 Comments
Macros & Operators

I know that many C++ programmers are not fans of the preprocessor. I think this is a real shame because it has so many incredibly wonderful uses.

For example: the arguments to a macro do not have to be variables or values!

Lets say that you are making a class that needs to define operators in a very standards way... like lets say you are wrapping strcmp() for comparing C strings and so you have a pretty standard way in which the operators will be implemented (this is actually pretty common).

Well rather than create one, and then copy and paste over and over (even using RegEx to make the changes to each paste can be a little tedious) you can use a macro and pass different operator symbols to it:

#define STR_MAKE_OPERATOR( op ) \
    bool operator##op (const Str &rhs) { \
        return (std::strcmp(this->strPtr, rhs.strPtr) op 0); \
    } 


Then you can make operators by just plugging in the right operator into the macro:

    STR_MAKE_OPERATOR(==);
    STR_MAKE_OPERATOR(!=);
    STR_MAKE_OPERATOR(>=);
    STR_MAKE_OPERATOR(<=);
    STR_MAKE_OPERATOR(<);
    STR_MAKE_OPERATOR(>);



In fact this pattern for creating operators can be so useful that I have created an include X-table for the comparison operators so that all I need to do is define an x-macro for the operator function and then #include the table.

So while avoiding macros like the plague may keep you safe from the evil bugs that *might* occur from their use, living on the edge a little can save you some aggravation in potential typos and repetitive copy/paste/modify routines.

Maybe you wish to avoid using macros in production code... well what about test code. Rather than writing up a customizing different tests for each operator -- you could just pass each operator as an argument to a preprocessor macro.

1 Comments On This Entry

Page 1 of 1

KYA 

05 June 2010 - 10:22 AM
This is sweet. Thanks NickDMax!
0
Page 1 of 1

May 2020

S M T W T F S
     12
3456789
10111213141516
17181920212223
24 25 2627282930
31      

Recent Entries

Search My Blog

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)