Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use macro to generate empty code for C++ class methods

Tags:

c++

macros

Let's say I have a class like below:

#define LOGGER_CLASS_ENABLED
    
#ifdef LOGGER_CLASS_ENABLED
        
class Logger{
public:
    void println(const String&);
};
    
Logger this_is_a_singleton_logger; 
    
#define MY_LOGGER this_is_a_singleton_logger
    
#endif

Throughout my code, whenever I want to log something, I use the following shortcut:

MY_LOGGER.println("Hello") 

Now, lets say I want to disable the Logger class. In this scenario, I don't want any logging code to be generated. So, the usual 'C-style' approach is this:

#ifdef LOGGER_CLASS_ENABLED  
MY_LOGGER.println("Hello");
#endif

and repeat it for every call.

However, since there are hundreds of such calls, surrounding each print function with an extra two lines everywhere will make the code hard to read. What should I do so that I don't add two lines everywhere, keeping the only a single line of MY_LOGGER.println("Hello"), but make the macro replace it with empty line. Is it possible?

I tried following but it gave me an error:

#ifndef LOGGER_CLASS_ENABLED
    
#define MY_LOGGER.println(x) // replace it with emtpiness
    
#endif
like image 863
UserRR Avatar asked Mar 13 '26 08:03

UserRR


1 Answers

Whereas having a macro "LOG"

#if defined(LOGGER_CLASS_ENABLED)
#define LOG(msg) MY_LOGGER.println(msg) 
#else
#define LOG(msg) do {} while(false)
#endif

would allow to entirely disable logging (and so msg is not evaluated, so LOG argument should not have side effect).

To keep usage MY_LOGGER.println(x) and does "nothing" (it is still evaluate x though, with its side effects) You might create a null object:

#ifdef LOGGER_CLASS_ENABLED
    
class RealLogger
{
public:
    void println(const String& msg) { /*Real logging*/}
};

using Logger = RealLogger;

#else // !LOGGER_CLASS_ENABLED

class NullLogger
{
public:
    void println(const String&) { /*empty*/ }
};

using Logger = NullLogger;

#endif

Logger this_is_a_singleton_logger; 
#define MY_LOGGER this_is_a_singleton_logger
like image 124
Jarod42 Avatar answered Mar 15 '26 22:03

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!