Skip to content

Instantly share code, notes, and snippets.

@lallousx86
Last active June 12, 2017 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lallousx86/7577dcb2605da8f338cf to your computer and use it in GitHub Desktop.
Save lallousx86/7577dcb2605da8f338cf to your computer and use it in GitHub Desktop.
AnsiOrWideString_t()
//--------------------------------------------------------------------------
#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