使用什么代替 `static const TCHAR *`
What to use instead of `static const TCHAR *`
许多旧 C/C++ 项目使用:
static TCHAR *x(_T("hello"));
... 来定义字符串,但是 ISO C++11 不允许从字符串文字转换为 TCHAR *
(又名 wchar_t *
),因此我正在寻找一种安全的替代方法写这些 static TCHAR *
行。
将它们更改为 std::wstring x(L"hello"))
会带来其他问题,例如 "already defined" 错误,那该怎么办?
您的问题是常量正确性问题,因此您不必触摸 static
(处理链接)。这个:
static std::wstring x = L"hello";
将与原始代码具有大致相同的含义。
可以通过多种方式获得该字符串数据的非常量 wchar_t *
:
- (C++17 及更高版本)
x.data()
;
&x[0]
(没有正式地 要求 以 nul 终止,但实现必须疯狂才能做到这一点)。这也可以包装在一个函数中,以避免与运算符优先级混淆:
wchar_t *data(std::wstring &string) { return &string[0]; }
为每个字符串声明一个伴随变量以保留一个标识符:
static std::wstring x = L"hello";
static wchar_t *x_c = &x[0];
#define staticTCHARptr( x , y ) static std::wstring _##x=y; static wchar_t *x = &_##x[0];
然后像这样使用它:
staticTCHARptr(X,L"hello");
而不是这个:
static TCHAR* X(_T("hello"));
现在所有原来用X的地方都不需要转换了
许多旧 C/C++ 项目使用:
static TCHAR *x(_T("hello"));
... 来定义字符串,但是 ISO C++11 不允许从字符串文字转换为 TCHAR *
(又名 wchar_t *
),因此我正在寻找一种安全的替代方法写这些 static TCHAR *
行。
将它们更改为 std::wstring x(L"hello"))
会带来其他问题,例如 "already defined" 错误,那该怎么办?
您的问题是常量正确性问题,因此您不必触摸 static
(处理链接)。这个:
static std::wstring x = L"hello";
将与原始代码具有大致相同的含义。
可以通过多种方式获得该字符串数据的非常量 wchar_t *
:
- (C++17 及更高版本)
x.data()
; &x[0]
(没有正式地 要求 以 nul 终止,但实现必须疯狂才能做到这一点)。这也可以包装在一个函数中,以避免与运算符优先级混淆:wchar_t *data(std::wstring &string) { return &string[0]; }
为每个字符串声明一个伴随变量以保留一个标识符:
static std::wstring x = L"hello"; static wchar_t *x_c = &x[0];
#define staticTCHARptr( x , y ) static std::wstring _##x=y; static wchar_t *x = &_##x[0];
然后像这样使用它:
staticTCHARptr(X,L"hello");
而不是这个:
static TCHAR* X(_T("hello"));
现在所有原来用X的地方都不需要转换了