简体   繁体   English

C++ 可变参数宏到可变参数函数

[英]C++ variadic macro to variadic function

Implementing an assertion macro I stumbled upon a problem on Xcode clang.实现断言宏我在 Xcode clang 上偶然发现了一个问题。

I use the following code:我使用以下代码:

void Log(LogLevel logLevel, const std::string& message);

std::string FormatString(const char* format, ...);

#define LOG(Level, Format, ...)                                     \
{                                                                   \
    std::string _ac_err_str_ = FormatString(Format, ##__VA_ARGS__); \
    Log(Level, _ac_err_str_);                                       \
}

#define checkf(expr, Format, ...)   { if(!(expr)) { LOG(LL_ErrorMessage, TXT("Log in file ") __FILE__ TXT(" at line %d: ") TXT(#expr) TXT(". ") Format, __LINE__, __VA_ARGS__); } }

Everything works fine with MSVC but on Clang I get the following error: Expected expression MSVC 一切正常,但在 Clang 上我收到以下错误: Expected expression

I've tracked down the problem on this line:我已经在这条线上找到了问题:

std::string _ac_err_str_ = FormatString(Format, ##__VA_ARGS__);

More specifically the problem is on the ##__VA_ARGS__ part because if I remove it everything compiles.更具体地说,问题出在##__VA_ARGS__部分,因为如果我删除它,一切都会编译。

Also, if I pass a third parameter to the macro it compiles, eg:另外,如果我将第三个参数传递给它编译的宏,例如:

checkf(false, "Error message");       // Won't compile
checkf(false, "Error %s", "message"); // Will compile

It seems like there's an error on passing the macro's variadic arguments to FormatString , but I can't find out the reason or how to fix this.似乎将宏的可变参数传递给FormatString出错,但我找不到原因或如何解决此问题。

Apparently on Clang I need to change my checkf macro like this显然在 Clang 我需要像这样改变我的checkf

#define checkf(expr, Format, ...)   { if(!(expr)) { LOG(LL_ErrorMessage, TXT("Log in file ") __FILE__ TXT(" at line %d: ") TXT(#expr) TXT(". ") Format, __LINE__, ##__VA_ARGS__); } }

Notice that I've used ##__VA_ARGS__ instead of just __VA_ARGS__ .请注意,我使用了##__VA_ARGS__而不是__VA_ARGS__

It compiles with both MSVC and Clang as well.它也可以使用 MSVC 和 Clang 进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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