Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token-pasting operator (##) is eating spaces in my C++ macro

I was having trouble with the following macro, and I found out that the token-pasting operator (##) is eating the space between static and the return type:

#define MY_FUNCTION(aReturnType) static ##aReturnType MyFunction() { }

So the preprocessor was turning this:

MY_FUNCTION(bool)

into this:

staticbool MyFunction() { }

which caused weird compilation errors.

I came up with the idea of putting parentheses around the static keyword:

// This works but is kind of weird
#define MY_FUNCTION(aReturnType) (static) ##aReturnType MyFunction() { }

Are there any better solutions?

like image 492
sourcenouveau Avatar asked Nov 22 '25 15:11

sourcenouveau


2 Answers

I think that your problem is that you don't want to use token pasting here. If you change the macro to

#define MY_FUNCTION(aReturnType) static aReturnType MyFunction() { }

Then if you write

MY_FUNCTION(bool)

it will expand out into

static bool MyFunction() { }

I am assuming that this is what you want to do, since I can't see what you're trying to paste the aReturnType argument to the macro onto.

Hope this helps!

like image 68
templatetypedef Avatar answered Nov 25 '25 08:11

templatetypedef


As it should do? You told it to paste together static and bool. If you don't want that and you want static bool instead, then don't paste them together?

like image 41
Puppy Avatar answered Nov 25 '25 06:11

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!