简体   繁体   English

gcc和clang预处理器不了解L前缀

[英]gcc and clang preprocessor doesn't understand L prefix

Assume this code: 假设此代码:

enum class Foo
{
    One,
    Two,
    Three,
    Four,
    Five
};

#define HANDLE_FOO(f) case Foo::f: std::wcout << L#f << std::endl;
Foo x = Foo::Five;
switch (x)
{
    HANDLE_FOO(One);
    HANDLE_FOO(Two);
    HANDLE_FOO(Three);
    HANDLE_FOO(Four);
    HANDLE_FOO(Five);
}    

msvc compiles it just right, but gcc gives this error: "'L' was not declared in this scope" msvc编译正确,但是gcc给出此错误:“在此作用域中未声明'L'”

So, the question is: how can I workaround this thing? 因此,问题是:如何解决该问题? Not only 'L' prefix doesn't work, but 'u' and so on doesn't work neither. 不仅'L'前缀不起作用,而且'u'等等也不起作用。

This code compiles just fine, though: 这段代码可以很好地编译:

std::wstring str = L"This is a string";

Thank you in advance. 先感谢您。

I believe that construct is invalid, and MSVC should diagnose it. 我认为该构造无效,MSVC应该对其进行诊断。

The # operator "stringizes" its argument, so One becomes "One" -- but by preceding it with L you have two separate tokens, L and "One" . #运算符将其参数“字符串化”,因此One变为"One" ,但是通过在L之前加上L您将获得两个单独的标记L"One"

What you want is a single token, the string literal L"One" . 您想要的是单个令牌,字符串文字L"One" You need to use the ## token-pasting operator as well as the # stringizing operator: 您需要使用##粘贴令牌运算符以及#字符串化运算符:

#define HANDLE_FOO(f) case Foo::f: std::wcout << L ## #f << std::endl;

Experiment shows that this works with both g++ 5.3.0 and clang++ 3.6. 实验表明,这适用于g ++ 5.3.0和clang ++ 3.6。

Checked with -E option of GCC, a space was produced between L prefix and the string in your code and I guessed the space is harmful. 用GCC的-E选项检查后, L前缀和代码中的字符串之间产生了一个空格,我猜该空格是有害的。

This code which uses ## operator to concatenate the tokens worked: 此代码使用##运算符来连接已工作的令牌:

#include <iostream>
enum class Foo
{
    One,
    Two,
    Three,
    Four,
    Five
};

#define HANDLE_FOO(f) case Foo::f: std::wcout << L## #f << std::endl;
int main(){
    Foo x = Foo::Five;
    switch (x)
    {
        HANDLE_FOO(One);
        HANDLE_FOO(Two);
        HANDLE_FOO(Three);
        HANDLE_FOO(Four);
        HANDLE_FOO(Five);
    }
}

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

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