简体   繁体   English

C ++预处理器连接操作

[英]C++ Preprocessor concatenation operation

I would like to use the C++ preprocessor concatenator. 我想使用C ++预处理器连接器。

#include <iostream>
#include <string>

#define GetBlack(colorName) (color.##colorName)

struct Color
{
    int black = 0;
};

int main()
{
  Color color;
  int c = color.black;
  int d = GetBlack(black); 
}

The error I get is 我得到的错误是

5:35: error: pasting "." 5:35:错误:粘贴“。” and "black" does not give a valid preprocessing token 并且“黑色”不提供有效的预处理令牌
16:11: note: in expansion of macro 'GetBlack' 16:11:注意:扩展宏'GetBlack'

C++Shell: C ++外壳:
http://cpp.sh/3547x http://cpp.sh/3547x

Any tips? 有小费吗?

You don't actually want concatenation here. 你实际上并不想在这里连接。 You are just pasting a preprocessing "token" into place, so just use: 你只是将预处理“令牌”粘贴到位,所以只需使用:

#define GetBlack(colorName) (color.colorName)

The macro argument name colorName is expanded in place. 宏参数名称colorName已在适当位置展开。 Then 然后

int d = GetBlack(black);

will expand into 将扩展到

int d = color.black;

Concatenation is for merging two "tokens" together into one, see here . 连接是将两个“令牌”合并为一个,见这里

For instance, if the member was named black_value , but you just wanted to have to call GetBlack(black) , the macro definition would be something like: 例如,如果该成员名为black_value ,但您只想调用GetBlack(black) ,则宏定义将类似于:

#define GetBlack(colourName) colour.colourName##_value;

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

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