【发布时间】:2019-09-29 20:53:21
【问题描述】:
有时需要为 char * 和 wchar_t * 类型创建具有相同值的字符串文字(例如,在 Windows 中开发时)。一个简单的方法是把定义写两次:
const char *my_string = "Hello World";
const wchar_t *my_wide_string = L"Hello World";
问题是如果我们需要改变字符串,而不是只改变一个地方,两行都需要更新,经常会导致拼写错误和错误。理想情况下,文字应该只出现一次,并且两个变量都由它填充。
我们可以定义char 变量并在运行时将其转换为wchar_t 版本。但是,最好避免运行时成本,因为字面量在编译时已经可用。
我想使用标记粘贴操作符,但不能让它工作,因为它只接受另一个字符串文字:
#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"
我不确定是否可以使用constexpr 使其工作?
【问题讨论】:
标签: c++ windows macros string-literals widechar