Last active
June 12, 2017 00:01
-
-
Save lallousx86/7577dcb2605da8f338cf to your computer and use it in GitHub Desktop.
AnsiOrWideString_t()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-------------------------------------------------------------------------- | |
#pragma warning(push) | |
#pragma warning(disable: 4127) | |
template <class DT, class ST> class AnsiOrWideString_t | |
{ | |
const DT *dstr; | |
bool bOwned; | |
AnsiOrWideString_t &operator =(const AnsiOrWideString_t &) { } | |
AnsiOrWideString_t(const AnsiOrWideString_t &) { } | |
public: | |
AnsiOrWideString_t(const DT *str) : dstr(str), bOwned(false) | |
{ | |
} | |
AnsiOrWideString_t(const ST *astr) : bOwned(true) | |
{ | |
dstr = NULL; | |
int count; | |
if (sizeof(ST) == 1) | |
{ | |
count = MultiByteToWideChar( | |
CP_UTF8, | |
0, | |
(LPCCH)astr, | |
-1, | |
NULL, | |
0); | |
} | |
else | |
{ | |
count = WideCharToMultiByte( | |
CP_UTF8, | |
0, | |
(LPCWCH)astr, | |
-1, | |
NULL, | |
0, | |
NULL, | |
NULL); | |
} | |
if (count == 0) | |
return; | |
DT *w = new DT[count + 1]; | |
int r; | |
if (sizeof(ST) == 1) | |
{ | |
r = MultiByteToWideChar( | |
CP_UTF8, | |
0, | |
(LPCCH)astr, | |
-1, | |
(LPWSTR)w, | |
count); | |
} | |
else | |
{ | |
r = WideCharToMultiByte( | |
CP_UTF8, | |
0, | |
(LPCWCH)astr, | |
-1, | |
(LPSTR)w, | |
count, | |
NULL, | |
NULL); | |
} | |
if (r == 0) | |
{ | |
delete[] w; | |
return; | |
} | |
w[count] = L'\0'; | |
dstr = w; | |
} | |
~AnsiOrWideString_t() | |
{ | |
if (bOwned) | |
delete[] dstr; | |
} | |
inline const DT *c_str() | |
{ | |
return dstr; | |
} | |
}; | |
#pragma warning(pop) | |
typedef AnsiOrWideString_t<wchar_t, char> WideString_t; | |
typedef AnsiOrWideString_t<char, wchar_t> AnsiString_t; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment