C++ 的调试宏带有变量参数但不带格式字符串
是否可以编写一个宏,它可以接受可变数量的参数并像这样扩展:
quickdebug(a) -> cout << #a ": " << a;
quickdebug(a,b) -> cout << #a ": " << a << #b ": "<< b;
等
如果没有,我是否可以至少打印所有参数而不给出格式字符串。例如
quickdebug2(a) -> cout << a ;
quickdebug2(a,b) -> cout << a << " " << b ;
,
在java中,我可以编写一个为我提供类似功能的函数:
void debug(Object...args)
{
System.out.println(Arrays.deepToString(args));
}
Is it possible to write a macro which can take in a variable number of arguments and expands like this :
quickdebug(a) -> cout << #a ": " << a;
quickdebug(a,b) -> cout << #a ": " << a << #b ": "<< b;
etc
If not, is it possible for me to at least print all the arguments without giving format strings. e.g
quickdebug2(a) -> cout << a ;
quickdebug2(a,b) -> cout << a << " " << b ;
etc
For example in java I can write a function which provides me similar functionality:
void debug(Object...args)
{
System.out.println(Arrays.deepToString(args));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过使用覆盖 , 运算符的类:
例如,您可以编写:
然后可以用预处理器宏包装:
因此您可以编写:
添加要在参数之间使用的 fi 分隔符字符串会很容易。
编辑:我刚刚添加了一个默认空格作为分隔符字符串。
By using a class that overrides , operator:
You can write for instance:
This can then be wrapped with a preprocessor macro:
So you can write:
It would be easy to add f.i. separator strings to be used between arguments.
Edit: I just added a default space as separator string.
可以创建一个可变参数的宏,从而采用可变数量的参数。语法类似于函数的语法:
参数列表中最后一个命名参数之后列出的任何参数都将列在 __VA_ARGS__ 中,包括任何分隔逗号。
所以:
quickdebug(1, 2, "123", 4.5)
变成functioncall("test", 1, 2 , "123", 4.5)
但是在某些时候你需要使用这些参数,如果没有格式字符串或其他指示参数类型的东西,这可能会变得非常困难。
问题是,当从变量参数列表中读取变量时,您需要知道参数的类型,或者至少知道它的大小。如果我是你,我会选择不同的方法。
您可以在此处阅读有关可变参数宏的更多信息: http://gcc.gnu.org/ onlinedocs/cpp/Variadic-Macros.html
It is possible to make a macro that is variadic thus taking a variable amount of arguments. The syntax is similar to that of a function:
Any argument listed after the last named argument in the argument list will be listed in
__VA_ARGS__
including any seperating comma.So:
quickdebug(1, 2, "123", 4.5)
becomesfunctioncall("test", 1, 2 , "123", 4.5)
However at some point you need to use these arguments, and here it can become extremely difficult if you don't have a format string, or something else indicating the type of the arguments.
The problem is that when reading variables from a variable arguments list, you need to know the type of the argument, or at least its size. If I were you I would choose a different approach.
You can read more about variadic macros here: http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html