我在Chromium项目中看到了C ++和JSON代码的混合。
这个宏是神奇吗?
#define LONG_STRING_CONST(...) #__VA_ARGS__
它如何“字符串化”任意JSON内容?
答案 0 :(得分:5)
Cameron的回答绝对正确。
但是,从C ++ 11开始,有一种编译器支持的方法来创建原始字符串文字。
char const *string = R"someToken({
"name": "software rendering list",
"version": "10.9",
"entries": [
{
"id": 1,
"description": "ATI Radeon X1900 is not compatible with WebGL on the Mac",
"webkit_bugs": [47028],
"os": {
"type": "macosx"
},
"vendor_id": "0x1002",
"device_id": ["0x7249"],
"features": [
"webgl",
"flash_3d",
"flash_stage3d"
]
},
{
"id": 3,
"description": "GL driver is software rendered. GPU acceleration is disabled",
"cr_bugs": [59302, 315217],
"os": {
"type": "linux"
},
"gl_renderer": "(?i).*software.*",
"features": [
"all"
]
}
]
})someToken";
但请注意,存在一些细微差别。
最明显的是,宏将摆脱C / C ++注释,宏将把所有空格合并到一个空格中。
有关字符串文字的更多详细信息可以在很多地方找到。我喜欢this one。
答案 1 :(得分:2)
你猜对了!
宏体内的 #
将后续标记转换为包含该标记文本的C字符串文字。在这种情况下,下一个标记是特殊的__VA_ARGS__
宏关键字,它被(variadic)宏的所有参数替换,它对应于源代码中的JSON。