Here’s a perfect example of token pasting in C++.
On about line 427 of WinNT.h, we see:
#define __TEXT(quote) L##quote
Now what this does is basically take any string you pass __TEXT( “some string” ) and prepend an L.
So in short it turns
__TEXT( "some string" )
into
L"some string"
So, its the magic of ## that makes it work. Basically when you write
#define __TEXT(quote) L##quote
You’re saying, ok, treat quote like a variable. In the last part of the #define we see ##quote, basically that is HOW YOU BACKREFERENCE the quote “variable” of the macro that was used earlier, in a “token pasting” way – basically you know that if you tried to write:
#define __TEXT(quote) Lquote
Then it would try and look for some symbol called Lquote, which basically doesn’t exist. What you want is to PREPEND AN L in front of (whatever quote is).
So,
#define __TEXT(quote) L##quote
The double pound ## there just says to “concatenate” or smush together the literal L (since L backreferences no symbol, it will resolve to the literal character ‘L’ at compile time), smush on there quote, which will backreference resolve into “some strong”
Here’s another one
// this: #define foreach( x, y, z ) for( vector<##x##>::iterator y = z.begin(); y != z.end(); ++y ) // turns: foreach( string, iter, infoVector ) // ( foreach string iter in infoVector ) // into: for(vector<string>::iterator iter = infoVector.begin(); iter != infoVector.end(); ++iter)