1

I am writing a macro which get std stream as arguments. For example

file.h

int enable = 0;
#define MYLOG(hanlde) \
    if (enable==0) { LOG1(handle) } \
    else { LOG2(handle) }

file.cpp

MYLOG(handle) << "Test log msg";

My intended result after preprocessor execution must be

LOG1(handle) << "Test log msg"; // if handle = 0
LOG2(handle) << "Test log msg"; // if handle = 1

Does this possible with macro in c++. If possible please provide the example.

sujin
  • 2,813
  • 2
  • 21
  • 33
  • 1
    The macro does not do much for your intended use. It might as well be a function. – R Sahu Mar 03 '16 at 04:11
  • @RSahu You are right my expectation is possible with function. But i don't want to do function call because it called from lots of places. – sujin Mar 03 '16 at 04:18
  • 2
    Simple `inline` functions are just as efficient as macros with modern compilers. They are better for other reasons too. See http://stackoverflow.com/questions/1137575/inline-functions-vs-preprocessor-macros. – R Sahu Mar 03 '16 at 04:25

2 Answers2

2

As written, your version of the MYLOG macro is clearly not going to expand out to valid C++ code.

The following alternative has a better chance of working as intended; however it also depends on what LOG1 and LOG2 really is

#define MYLOG(handle) (enable == 0 ? LOG1(handle):LOG2(handle))
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
2

The macro, as presented, will not work. You'll need to use something like:

#define MYLOG(hanlde) \
    (enable == 0 ? LOG1(handle) : LOG2(handle))

Having said that, you can use an inline function that works just as well.

inline std::ostream& MYLOG(handle_type handle)
{
    return (enable == 0 ? LOG1(handle) : LOG2(handle))
}

Simple inline functions are just as efficient as macros with modern compilers. They are better for other reasons too. See Inline functions vs Preprocessor macros.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270