Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MSVC preprocessor 'charizing' operator in Clang

I've got the following code that someone working on MSVC has given to me:

#define MAP1(x, y) map[#x] = #@y;

I'm on Xcode, using Clang, and from various google searches I've found that this is known as a 'charizing operator', and is specific to MSVC's preprocessor. Is there a way of emulating the functionality of this operator while using Clang? I've tried removing the @ but got the following error message:

Assigning to 'int' from incompatible type 'const char[2]'

Would an explicit cast to 'int' work or is the charizing operator doing something different?

like image 290
benwad Avatar asked Sep 17 '25 23:09

benwad


2 Answers

The stringizing operator (standard C++) converts a into "a", so the charizing operator sounds like it turns a into 'a'. You can, in the simple cases, get 'a' from "a" by taking the first character.

#define MAP1(x, y) map[#x] = static_cast<const char(&)[2]>(#y)[0];

The static_cast to const char(&)[2] ensures you get a compile-time error if you don't get a string of length 1, which is two characters if you count the trailing '\0'. A plain #y[0] would silently take the first character, regardless of the string's length.

Did you try something like #y[0]? Basically, "stringify y and take the first char" :-)

Other than that, since from the looks of it the generated statements are executed at runtime anyway, you can just stringify y, pass it to a function and have that function return the right thing.

like image 34
Christian Stieber Avatar answered Sep 19 '25 13:09

Christian Stieber