考虑下面的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 ++抱怨无效令牌。编译器突出显示>
,但这不是宏生成的代码。
答案 0 :(得分:3)
在第
行static Smanip<void> ##what##Allign()
您尝试连接>
和what
。尝试使用
static Smanip<void> what##Allign()