c++ - g++ 在宏上提示 "does not give a valid preprocessing token"而 vc++ 编译正常

标签 c++ visual-c++ macros g++

考虑以下使用 VC++ 编译但无法使用 g++ 编译的 C++ 程序

D:\temp>cat test.cpp
#define SET_ALLIGN_FN(what)                            \
        void set_##what##_fn() { }
        SET_ALLIGN_FN(Left);
#undef SET_ALLIGN_FN
    template<class _Arg> struct Smanip{
            Smanip(void( *pFun)(_Arg), _Arg val):m_pFun(pFun), m_val(val) { }
        void( *m_pFun)(_Arg);
        _Arg m_val;
    };
    template<>  struct Smanip<void> {
        Smanip(void( *pFun)()) : m_pFun(pFun) { }
        void( *m_pFun)();
    };
#define SET_ALLIGN(what)                                      \
    static Smanip<void>  ##what##Allign()                     \
    { return (Smanip<void>(set_##what##_fn)); }
    SET_ALLIGN(Left);
#undef SET_ALLIGN

int main() {  }
D:\temp>cl test.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.61030 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
Microsoft (R) Incremental Linker Version 11.00.61030.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj

D:\temp>g++ test.cpp
test.cpp:15:23: error: pasting ">" and "Left" does not give a valid preprocessin
g token
     static Smanip<void>  ##what##Allign()  { return (Smanip<void>(set_##what##_
fn)); }
                       ^
test.cpp:16:5: note: in expansion of macro 'SET_ALLIGN'
     SET_ALLIGN(Left);
     ^

我不明白的是为什么 g++ 提示无效 token 。编译器突出显示 >,但这不是宏生成的代码。

最佳答案

行内

static Smanip<void>  ##what##Allign()

您尝试连接 >what。尝试使用

static Smanip<void>  what##Allign()

关于c++ - g++ 在宏上提示 "does not give a valid preprocessing token"而 vc++ 编译正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25241217/

相关文章:

scala - 如何在 Scala 中访问宏注释中的泛型类型?

c++ - 用 lambda 替换纯虚拟接口(interface)

c++ - 调用cudaMemcpy2DToArray时访问违规读取位置

visual-c++ - 在不同嵌套级别的多个项目中包含公共(public)资源(Visual C++)

c 宏,数组定义作为参数

c - 预处理器如何进行扩展(在包含的头文件中定义宏)

c++ - 从另一个程序向可执行文件发送参数

c++ - 如何使用 c++ 将字符串散列为 int?

在用户插入的字符串的每个元音后插入一对字符的 C++ 代码

c++ - 如何在不更改的情况下检索当前的 terminate() 处理程序?