G++ 抱怨宏"does not give a valid preprocessing token",而 VC++ 编译良好

g++ complains "does not give a valid preprocessing token" on a macro while vc++ compiles fine

本文关键字:token VC++ preprocessing 编译 does not G++ give valid      更新时间:2023-10-16

考虑下面的c++程序,它可以用vc++编译,但不能用g++编译

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++抱怨无效的令牌。编译器突出显示>,但这不是宏生成的代码。

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

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

static Smanip<void>  what##Allign()