简体   繁体   English

使用C中的宏生成函数

[英]Generate functions using Macros in C

I have the following macro: 我有以下宏:

‎#define GTR(type) \‎
type type##_gtr(type a, type b) \‎
‎{ \‎
‎   return a > b ? a : b;\‎
‎}‎

I understand that it generates functions, but if GTR(unsigned int) expands outside main() , how do I call the generated function? 我知道它生成函数,但如果GTR(unsigned int)扩展到main()之外,我该如何调用生成的函数? _gtr(a, b) does not work... _gtr(a, b)不起作用......

You would have to write unsigned int_gtr(a,b) so it would not work for that type with the macro definition you have created. 您必须编写unsigned int_gtr(a,b)因此它对于您创建的宏定义不适用于该类型。

The reason is that the preprocessor simply replaces the type parameter and joins it to the text after the ##. 原因是预处理器只是替换了type参数并将其连接到##之后的文本。

You could do something like create a typedef for unisgned int so there were no spaces and then use that, eg: 你可以做一些事情,比如为unisgned int创建一个typedef所以没有空格然后使用它,例如:

typedef unsigned int uint;
GTR(uint)
...
uint_gtr(a,b)

This: 这个:

type##_gtr

inside the macro is glueing together the value of the type argument with the text _gtr . 宏内部正在将type参数的值与文本_gtr粘合在一起。 This happens between the return type and the opening parenthesis of the argument list, ie this forms the name of the function. 这发生在返回类型和参数列表的左括号之间,即这形成了函数的名称。

So if you use GTR(unsigned int) , you fail since the full function prototype ends up looking like this: 因此,如果您使用GTR(unsigned int) ,则会失败,因为完整的函数原型最终看起来像这样:

unsigned int unsigned int_gtr(unsigned int a, unsigned int b)

which is not syntactically correct. 这在语法上是不正确的。 Basically, the macro has a weakness in that it assumes type names cannot contain spaces, which is not true in C. 基本上,宏有一个缺点,它假定类型名称不能包含空格,这在C中不是这样。

If you use GTR(unsigned) , though, you should call it as unsigned_gtr() . 但是,如果使用GTR(unsigned) ,则应将其称为unsigned_gtr()

GTR(unsigned) would expand to: GTR(unsigned)将扩展为:

unsigned unsigned_gtr(unsigned a, unsigned b)
{
‎   return a > b ? a : b;
}‎

In that case, you should call unsigned_gtr(a, b) . 在这种情况下,您应该调用unsigned_gtr(a, b)

GTR(unsigned int) , however, would fail with a syntax error because you are having two separate tokens and the name of the function cannot be properly produced. 但是, GTR(unsigned int)会因语法错误而失败,因为您有两个单独的标记,并且无法正确生成函数的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM