Sometimes there is need to create string literals with the same value for both char *
and wchar_t *
types (e.g. when developing in Windows). A simply way is to write the definition twice:
const char *my_string = "Hello World";
const wchar_t *my_wide_string = L"Hello World";
The problem is that if we need to change the string, instead of just changing one place, both lines need to be updated, often lead to typos and bugs. Ideally the literal should only appear once and both variables are populated from it.
We could define the char
variable and convert it to the wchar_t
version at runtime. However, it is better to avoid the runtime cost since the literal is already available at compile time.
I thought to use the token-pasting operator, but can't make it work because it only accepts another string literal:
#define my_string "Hello World"
#define make_wide(str) L##str
#define my_wide_string make_wide(my_string) // expand to Lmy_string instead of L"Hello World"
I'm not sure if one can use constexpr
to make it work?
You just need another macro so the argument of the macro is expanded before pasting:
#include <wchar.h>
#define my_string "Hello World"
#define WidenHelper(x) L##x
#define Widen(x) WidenHelper(x)
const char *plain = my_string;
const wchar_t *wide = Widen(my_string);