[英]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 函数
DebugLog(QString, unsigned int Verbosity = 1)
具有可选参数Verbosity,我想在宏中也可选,这样我就可以调用
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
注意:我在宏中使用第二个变量,但如果我没有它,我可以将其替换为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: 看到你已经使用了宏,你可能不会介意一个非常hacky的解决方案:
#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
. (bool)"abc"
为true
,所以(int)(bool)"abc"
为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
. (int)(bool)"abc", 10
使用逗号运算符,因此它的计算结果为10
。
But please please , consider using an inline
function instead. 但请, 请考虑使用
inline
函数。 There's no need to use a macro for this. 没有必要为此使用宏。
There is also a solution with Boost.Preprocessor : 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
. 它比使用逗号运算符的方法更灵活,因为您可以使用任何默认参数,而不仅仅是
1
。
Still: Use inline functions (or Lambdas). 仍然:使用内联函数(或Lambdas)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.