2

Let's say I have a macro

#define CLASS_NAME ItemsList

Later I would like to use the value of it, not as a symbol, but as wide string. And my problems begin. When I simply write (in a regular C++ code, not in macro definition):

L#CLASS_NAME

compiler gives me an error, saying token # was not expected here. When I write proxy for it

#define WSTRING(S) L#S

and use it

WSTRING(CLASS_NAME)

I will get wide string with content "CLASS_NAME". I would like to expand macro, meaning getting its value, not converting the macro name.

So how to do it properly (Visual Studio 2012)?

greenoldman
  • 16,895
  • 26
  • 119
  • 185

1 Answers1

3

If you want L"ItemsList" then you can use:

#define CONCAT2(X, Y) X##Y
#define CONCAT(X, Y) CONCAT2(X, Y)
#define STRINGIFY2(X) #X
#define STRINGIFY(X) STRINGIFY2(X)
#define WIDEN(X) CONCAT(L, STRINGIFY(X))

And then write WIDEN(CLASS_NAME).

Simple
  • 13,992
  • 2
  • 47
  • 47
  • You have a typo on the definition, `WIDEN` should expand to `WIDEN2`. But the more important issue is that `WIDEN(CLASS_NAME)` as written will expand to L"CLASS_NAME", because the `#` is on the first level of expansion. It has to be on the second level of expansion to actually expand the parameter. – Jan Hudec Jan 14 '14 at 14:51
  • See also http://stackoverflow.com/questions/2751870/how-exactly-does-the-double-stringize-trick-work – Jan Hudec Jan 14 '14 at 14:52
  • @JanHudec Right you are. – Simple Jan 14 '14 at 14:58
  • Thank you, but even with fixed type I still get `CLASS_NAME` as the result. – greenoldman Jan 14 '14 at 14:58
  • Million thanks (I wouldn't solve it by myself, no way :-D), it works like a charm. – greenoldman Jan 14 '14 at 15:06
  • Thanks works perfectly! And thanks also to the author of the question for having asked it! I could never have figured it out by myself. Just, it is a bit a disappoint to me that c++ does not allow any easier and more compact/intuitive way to do a simple job as expanding a macro to a wide string! – elena Dec 05 '22 at 22:33