I'm making some win32 string API calls and am assuming that the strings come out as wide strings, which is valid on XP and newer. How can I assert this? Is this a runtime check or a compile-time check?
Am I doing it wrong? Here's an example:
typedef std::basic_string<TCHAR> TString;
inline TString queryRegStringValue(HKEY key, const TString& subkey,
const TString defaultValue = TEXT(""))
{
std::vector<char> out_bytes(256);
DWORD num_bytes = out_bytes.size();
DWORD out_type;
long retval = RegQueryValueEx(key, subkey.c_str(), 0, &out_type,
reinterpret_cast<BYTE*>(&out_bytes[0]), &num_bytes); //comes out as a platform string. wide on XP
if (retval != 0)
return defaultValue;
if (num_bytes > 0)
{
assert(out_type == REG_SZ);
BOOST_STATIC_ASSERT(sizeof(TCHAR)==2); //what if someone runs my code on an older system?
开发者_StackOverflow中文版return TString(reinterpret_cast<wchar_t*>(&out_bytes[0]), num_bytes/2); //assumes windows XP (wide string)
}
return TEXT("");
}
It is a non-issue. Windows has been a native Unicode operating system for the past 17 years, long before XP was released. David Cutler's brain child, NT 3.1, was Unicode from day one.
In the unlikely case that your program lands on a Window 9x machine, there's still an API layer that can translate your UTF-16 strings to 8-bit chars. There's no point left in using TCHAR for new code development.
I think this MSDN article is what you're looking for. You want to know what version of windows you're on, and adjust your string handling as appropriate? If i misunderstood, please feel free to leave a comment and i'll adjust my answer.
http://msdn.microsoft.com/en-us/library/ms724429.aspx
I think what's going on is that when I compile, I compile against the Unicode windows APIs, so if I run my executable on a non-widechar windows, it will fail to run. Thus a runtime check is useless.
I added the compile-time assertion to force a build-error if we compile on a non-widechar platform (pre XP, or pre 2000, or whatever it is) the build will fail. If the assertion weren't there it would fail anyway, but more cryptically.
精彩评论