May 9, 2018

[macro] ## parse tokens

https://stackoverflow.com/questions/49937805/c-macro-doesnt-work-after-operator

detailed answer:
https://stackoverflow.com/a/41691582

GCC Doc:
https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

GCC Doc, Macro:
https://gcc.gnu.org/onlinedocs/cpp/Macros.html#Macros


# : produce string type.
## : concatenate 2 operand into single text, not string type.


The token-pasting operator (##) is used to concatenate two tokens into a single valid token.


When write
x->##type##_value();


The first processed token is x.

The next token is formed by concatenating the token -> with type, since type is a, the result of the concatenation is ->a, which ought to be a valid token, but is not.

Hence, you get the error: pasting formed '->a', an invalid preprocessing token.

To fix this, just write
x->type##_value();

This way:
  • The first token parsed is x.
  • The next token parsed is ->.
  • The next token is formed by concatenating the token type (which becomes a) with the token _value. This gives a_value, which is a valid token.
  • The next token is (.
  • The next token is ).
  • The last token is ;.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.