简体   繁体   中英

C++ use a number of arguments in variadic macro (implementing optional argument)

I am writing some macro (yes I know it's evil, but it helps me make more optimized code) that looks like this:

#define HUGGLE_DEBUG(debug, verbosity) if (Huggle::Configuration::HuggleConfiguration->Verbosity >= verbosity) \
                                          Huggle::Syslog::HuggleLogs->DebugLog(debug, verbosity)

function DebugLog(QString, unsigned int Verbosity = 1) has optional parameter Verbosity and I would like to make it optional in macro as well, so that I can call

HUGGLE_DEBUG("some debug text");

as well as:

HUGGLE_DEBUG("more verbose text", 10);

Is it somehow possible? Note: I am using the second variable in macro, but if I didn't have it, I could just substitute it to 1

My idea is to make a variadic macro from this, which would work like this:

#define HUGGLE_DEBUG(debug, ...)    Syslog::HuggleLogs->DebugLog(debug, ##__VA_ARGS__)

which would work but it would kind of not use the optimization I did in first one

Seeing as you're using a macro already, you probably won't mind a very hacky solution:

#define HUGGLE_DEBUG(...) \
  if (Huggle::Configuration::HuggleConfiguration->Verbosity >= ((int)(bool)__VA_ARGS__)) \
    Huggle::Syslog::HuggleLogs->DebugLog(__VA_ARGS__)

When called with one argument:

HUGGLE_DEBUG("abc")

// expands to

if (Huggle::Configuration::HuggleConfiguration->Verbosity >= ((int)(bool)"abc"))
    Huggle::Syslog::HuggleLogs->DebugLog("abc")

(bool)"abc" is true , so (int)(bool)"abc" is 1 .

When called with two arguments:

HUGGLE_DEBUG("abc", 10)

// expands to

if (Huggle::Configuration::HuggleConfiguration->Verbosity >= ((int)(bool)"abc", 10))
    Huggle::Syslog::HuggleLogs->DebugLog("abc", 10)

(int)(bool)"abc", 10 uses the comma operator, so it evaluates to 10 .

But please please , consider using an inline function instead. There's no need to use a macro for this.

There is also a solution with Boost.Preprocessor :

#define HUGGLE_DEBUG_1( debug ) HUGGLE_DEBUG_2( debug, 1 )
#define HUGGLE_DEBUG_2( debug, verbosity ) \
if( Huggle::Configuration::HuggleConfiguration->Verbosity >= verbosity) \
    Huggle::Syslog::HuggleLogs->DebugLog(debug, verbosity)

#define HUGGLE_DEBUG( ... ) BOOST_PP_OVERLOAD(HUGGLE_DEBUG_,__VA_ARGS__) (__VA_ARGS__)

It is more flexible than the approach using the comma operator, since you can use any default argument, not just 1 .

Still: Use inline functions (or Lambdas).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM