预处理器使用字符串文字前缀对运算符进行字符串化

Jon*_*Mee 3 macros string-literals stringification c-preprocessor

所以我想做传统的事情来处理宏中的字符串化运算符:

#define FOO(x) foo(#x, (x))
Run Code Online (Sandbox Code Playgroud)

但是我需要使用字符串文字前缀:http://en.cppreference.com/w/cpp/language/string_literal
这是一个问题,因为如果我需要一个UTF-32字符串文字我尝试这样做:

#define FOO(x) foo(U#x, (x))
Run Code Online (Sandbox Code Playgroud)

但gcc 4.9.2抱怨:

错误:在此范围内未声明'U'

有没有办法让编译器将其U作为字符串化宏变量的前缀?

chr*_*ris 5

是的,使用连接:

#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))
Run Code Online (Sandbox Code Playgroud)

额外的间接,除了好的,如果你传递一个应该首先评估的宏,是"需要的"因为N3936§16.3.2[cpp.stringize]/2,它说:

#和##运算符的求值顺序未指定.