I recently read Scott Meyers' Effective C ++ Second Edition to improve best practices in C ++. One of its elements encourages C ++ programmers to avoid preprocessor macros and "prefers the compiler." He went so far as to say that there are almost no reasons for macros in C ++, except for #include and # ifdef / # ifndef.
I agree with his reasoning, as you can run the following macro
with the following C ++ language features
template<class T> inline const T & min(const T & a, const T & b) { return a < b ? a : b; }
where inline gives the compiler the ability to remove a function call and insert inline code and a template that can handle several types of data that have an overloaded or inline operator>.
EDIT - . The declaration of this template will not fully match the specified macro if the data types a and b are different. See Pete's Comment for an example.
However, I'm curious to know if using macros to debug logging is a valid use in C ++. If the method below is not good practice, would anyone be kind enough to suggest an alternative way?
I encoded in Objective-C over the past year, and one of my favorite 2D engines (cocos2d) used a macro to create registration statements. The macro is as follows:
#define __CCLOGWITHFUNCTION(s, ...) \ NSLog(@"%s : %@",__FUNCTION__,[NSString stringWithFormat:(s), ##__VA_ARGS__]) #define __CCLOG(s, ...) \ NSLog(@"%@",[NSString stringWithFormat:(s), ##__VA_ARGS__]) #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 #define CCLOG(...) do {} while (0) #define CCLOGWARN(...) do {} while (0) #define CCLOGINFO(...) do {} while (0) #elif COCOS2D_DEBUG == 1 #define CCLOG(...) __CCLOG(__VA_ARGS__) #define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) #define CCLOGINFO(...) do {} while (0) #elif COCOS2D_DEBUG > 1 #define CCLOG(...) __CCLOG(__VA_ARGS__) #define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) #define CCLOGINFO(...) __CCLOG(__VA_ARGS__) #endif
This macro provides incredible utility that I want to include in my C ++ programs. Writing a useful log statement is as easy as
CCLOG(@"Error in x due to y");
What's even better is that if COCOS2D_DEBUG is set to 0, then these statements never see the light of day. There is no overhead to verify the conditional statement to see if you should use the logging instructions. This is convenient when moving from development to production. How can I recreate the same effect in C ++?
So, does this type of macro belong to a C ++ program? Is there a better, more C ++ way to do this?