Preprocessor Stringizing Operator with String Literal Prefixes

孤人 提交于 2019-12-10 21:49:45

问题


So I want to do the traditional thing to do with the stringizing operator in a macro:

#define FOO(x) foo(#x, (x))

However I need to use a string literal prefix: http://en.cppreference.com/w/cpp/language/string_literal
Which is a problem because if I need a UTF-32 string literal I try to do this:

#define FOO(x) foo(U#x, (x))

But gcc 4.9.2 complains:

error: 'U' was not declared in this scope

Is there a way to make the compiler treat the U as a prefix to the stringized macro variable?


回答1:


Yes, use concatenation:

#define CONCAT2(x, y) x ## y
#define CONCAT(x, y) CONCAT2(x, y)
#define STRINGIZE(x) #x

#define FOO(x) foo(CONCAT(U, STRINGIZE(x)), (x))

The extra indirection, besides being good if you pass a macro that should be evaluated first, is "needed" because of N3936 §16.3.2 [cpp.stringize]/2, which says:

The order of evaluation of # and ## operators is unspecified.



来源:https://stackoverflow.com/questions/29850088/preprocessor-stringizing-operator-with-string-literal-prefixes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!