C++ 来自宏参数的变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7561828/
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-28 17:08:13  来源:igfitidea点击:

Variable name from macro argument

c++c-preprocessor

提问by Paul Manta

I'd like to do something like this:

我想做这样的事情:

class SomeClass { };

GENERATE_FUNTION(SomeClass)

The GENERATE_FUNCTIONmacro I'd like to define a function whose name is to be determined by the macro argument. In this case, I'd like it to define a function func_SomeClass. How can that be done?

GENERATE_FUNCTION宏我想定义的名字是由宏参数确定的函数。在这种情况下,我希望它定义一个函数func_SomeClass。那怎么办呢?

回答by K-ballo

#define GENERATE_FUNCTION(Argument) void func_##Argument(){ ... }

More information here: http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation

更多信息在这里:http: //en.wikipedia.org/wiki/C_preprocessor#Token_concatenation

回答by Dmitri

As everyone says, you can use token pasting to build the name in your macro, by placing ##where needed to join tokens together.

正如大家所说,您可以使用标记粘贴在宏中构建名称,方法是放置##需要将标记连接在一起的位置。

If the preprocessor supports variadic macros, you can include the return type and parameter list too:

如果预处理器支持可变参数宏,您也可以包含返回类型和参数列表:

#define GENERATE_FUNCTION(RET,NAM,...) RET func_##NAM(__VA_ARGS__)

..so, for example:

..所以,例如:

GENERATE_FUNCTION(int,SomeClass,int val)

..would expand to:

..将扩展为:

int func_SomeClass(int val)

回答by Tim Cooper

#define GENERATE_FUNCTION(class_name) func_##class_name##