[英]Calling a printf with __VA_ARGS__ not working in a function but works in a macro
The following macro works:以下宏有效:
#define DEBUG(msg, ...) printf(msg, __VA_ARGS__)
But when I add my own function, it says error: '__VA_ARGS__' was not declared in this scope
.但是当我添加我自己的 function 时,它
error: '__VA_ARGS__' was not declared in this scope
。 My code:我的代码:
void Debug(const char* msg, ...) {
printf(msg, __VA_ARGS__);
}
#define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)
Is there any way to do so?有什么办法吗?
Variadic parameter pack is your friend in this case:在这种情况下,可变参数包是您的朋友:
template< typename ... Args >
void Debug( const char * msg, Args ... args ) {
printf( msg, args ... );
}
__VA_ARGS__
simply does not exist outside of a variadic macro. __VA_ARGS__
根本不存在于可变参数宏之外。 For what you are attempting, use vprintf()
instead of printf()
, eg:对于您正在尝试的内容,请使用
vprintf()
而不是printf()
,例如:
void Debug(const char* msg, ...) {
va_list args;
va_start(args, msg);
vprintf(msg, args);
va_end(args);
}
#define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.