如何使用宏参数作为字符串文字? [英] How to use Macro argument as string literal?

查看:349
本文介绍了如何使用宏参数作为字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何编写一个宏,该宏将变量名的字符串文字表示形式以及变量本身传递到函数中。

I am trying to figure out how to write a macro that will pass both a string literal representation of a variable name along with the variable itself into a function.

例如,给定以下函数。

void do_something(string name, int val)
{
   cout << name << ": " << val << endl;
}

我想写一个宏,所以我可以这样做:

I would want to write a macro so I can do this:

int my_val = 5;
CALL_DO_SOMETHING(my_val);

将打印出以下内容: my_val:5

我尝试执行以下操作:

#define CALL_DO_SOMETHING(VAR) do_something("VAR", VAR);

但是,您可能会猜到,引号内的VAR不会被替换,而只是作为字符串文字 VAR传递。因此,我想知道是否有一种方法可以将宏参数本身转换为字符串文字。

However, as you might guess, the VAR inside the quotes doesn't get replaced, but is just passed as the string literal "VAR". So I would like to know if there is a way to have the macro argument get turned into a string literal itself.

推荐答案

使用预处理程序 运算符

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

这篇关于如何使用宏参数作为字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆