C++ 如何使用宏参数作为字符串文字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10507264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:09:14  来源:igfitidea点击:

How to use Macro argument as string literal?

c++c-preprocessorstring-literals

提问by Ian

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.

我想弄清楚如何编写一个宏,将变量名的字符串文字表示和变量本身传递给函数。

For example given the following 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);

Which would print out: my_val: 5

哪个会打印出来: my_val: 5

I tried doing the following:

我尝试执行以下操作:

#define CALL_DO_SOMETHING(VAR) do_something("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.

但是,正如您可能猜到的,引号内的 VAR 不会被替换,而只是作为字符串文字“VAR”传递。所以我想知道是否有办法让宏参数本身变成字符串文字。

回答by Morwenn

Use the preprocessor #operator:

使用预处理器#运算符

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

回答by chris

You want to use the stringizing operator:

您想使用字符串化运算符:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

回答by Mikele Shtembari

#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

回答by Zili

Perhaps you try this solution:

也许你试试这个解决方案:

#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . . 
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";