宏名称扩展语法 [英] Macro name expansion syntax

查看:53
本文介绍了宏名称扩展语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始尝试使用宏来生成数据结构.,我遇到了一个奇怪的障碍.我要编写以下宏:

  #define CREATE_STRUCT(NAME)结构## NAME {} 

我试图这样使用它:

  CREATE_STRUCT(测试); 

但是,它生成一个错误,并且宏扩展显然不起作用.我注意到,在我所看到的这种宏扩展类型的每个示例中,在 ##< ARG> 标记之前都有一个下划线( _ ).例如:

  #define CREATE_STRUCT(NAME)结构_ ## NAME {} 

这是可行的,但是它当然会在新声明的类型的开头加上下划线.

因此,这里有几个问题:

  1. 有没有一种方法可以避免在 ## 令牌之前要求字符?
  2. 关于宏中 ## 令牌的规则是什么?

提前谢谢!

解决方案

除非您希望将多个令牌合并为一个,否则不需要令牌粘贴运算符.例如,从Test and This获取TestThis.就您而言,您可以这样做:

  #define CREATE_STRUCT(NAME)结构名称{} 

如果在宏上运行 g ++ -E file.cc ,则会看到预处理器附带了 structtest {}; ,这将导致错误./p>

I'm starting a foray into using macros to generate data structures. Alas, I've run into a strange snag. I want to write the following macro:

#define CREATE_STRUCT(NAME) struct ##NAME { }

I attempt to use it like this:

CREATE_STRUCT(test);

However, it generates an error and the macro expansion apparently doesn't work. I've noticed that in every example of this type of macro expansion I've seen, there is an underscore (_) that precedes the ##<ARG> token. For example:

#define CREATE_STRUCT(NAME) struct _##NAME { }

This one works, but of course it throws an underscore at the beginning of the newly declared type.

So, there's a few questions here:

  1. Is there a way to avoid requiring a character to precede the ## token?
  2. What are the rules regarding the ## token in macros?

Thank you in advance!

解决方案

You don't need the token pasting operator unless you want to merge multiple tokens into one. For example get TestThis from Test and This. In your case you can just do:

 #define CREATE_STRUCT(NAME) struct NAME { }

If you run g++ -E file.cc on your macro, you will see that the preprocessor comes up with structtest { }; and this causes an error.

这篇关于宏名称扩展语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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