jemin jemin - 24 days ago 5
C++ Question

A macro failed to use decltype(X) in g++

I've written a macro --- swapMacro and its 2 sub macros as below.

#define swapMacro( X, Y) swap_Macro1( X, Y, decltype(X) )
#define regTMP tmp ## __LINE__ ## __FILE__
#define swap_Macro1( X, Y, ARG_TYPE ) \
do { \
register ARG_TYPE regTMP; \
swap_Macro2( (X), (Y), regTMP); \
} while( 0);
#define swap_Macro2( X, Y, T) \
{ \
(T)= (X);\
(X)= (Y);\
(Y)= (T);\

And here is the code to test them.

int a= 110;
int b= 220;
register int t;
swap_Macro2 ( a, b, t); // works perfect, only 2 mem/r + 2 mem/w operations
swap_Macro1 ( a, b, int ); // works, as same as swap_Macro2
swapMacro ( a, b); // this one works if cflag -std=c++11 is set

int *A= new int(10);
int *B= new int(10);
A[0]= 330;
B[0]= 440;
swapMacro ( (A[0]), B[0]); // failed, even -std=c++11 is set
swapMacro ( A[0], B[0]); // failed, even -std=c++11 is set. However, the solution provide by Anton Savin solve it

But if I use Visual C++ 2010 to do that again, all 3 macros work, although they all need 3 mem/r and 3 mem/w operations ( watched from the debugger windows).
I wonder if there is any proper syntax to write swapMacro(a,b) for use of g++ ?


As I wrote in a comment, your code works for me. However, I believe the reason for the error is that you added extra parentheses somewhere, like this:

swapMacro ((a), b);

In this case, decltype(X) becomes decltype((a)) and that is not int now but int&.

To fix it you can change swapMacro definition by

#define swapMacro( X, Y) swap_Macro1( X, Y, std::remove_reference<decltype(X)>::type )

That said, I don't quite understand the purpose of all these macros and why you don't just use std::swap().