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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With