This contribution was first inspired by
this thread's[
^] question and
Stephen Hewitt [
^]answers.
It was heavily edited to address Aescleal's interesting concerns and remarks.
This (last) version compiles with VS2008 and VS2010 (native Standard C++ Library) without warning at level 4.
The two
LoadString()
functions are independant of the application character set and return the length of the destination string, as does
::LoadString()
.
template <class StringType> StringType LoadString_()
is a helper class using the matching
LoadString()
version to build a
StringType
with uID string resource content.
LoadString_W()
returns a
std::wstring
with uID string resource content (empty if no resource).
LoadString_S()
returns a
std::string
with uID string resource content (empty if no resource).
LoadString_T()
returns a
UNICODE
depending
std::wstring
or
std::string
, with
uID string
resource content (empty if no resource).
#include <string>
#include <Windows.h>
#include "resource.h"
inline int LoadString(std::wstring& wsDest, UINT uID, HINSTANCE hInstance = ::GetModuleHandle(NULL))
{
PWCHAR wsBuf; wsDest.clear();
if (size_t len = ::LoadStringW(hInstance, uID, (PWCHAR)&wsBuf, 0))
wsDest.assign(wsBuf, len);
return wsDest.length();
}
inline int LoadString(std::string& sDest, UINT uID, HINSTANCE hInstance = ::GetModuleHandle(NULL))
{
PWCHAR wsBuf; sDest.clear();
if (size_t len = ::LoadStringW(hInstance, uID, (PWCHAR)&wsBuf, 0) * sizeof WCHAR)
{
sDest.resize(++len); sDest.resize(::LoadStringA(hInstance, uID, &*sDest.begin(), len));
}
return sDest.length();
}
template <class StringType>
inline StringType LoadString_(UINT uID, HINSTANCE hInstance)
{
StringType sDest;
return LoadString(sDest, uID, hInstance) ? sDest : StringType();
}
inline std::string LoadString_S(UINT uID, HINSTANCE hInstance = ::GetModuleHandle(NULL))
{
return LoadString_<std::string>(uID, hInstance);
}
inline std::wstring LoadString_W(UINT uID, HINSTANCE hInstance = ::GetModuleHandle(NULL))
{
return LoadString_<std::wstring>(uID, hInstance);
}
#ifdef UNICODE
typedef std::wstring t_string;
#else
typedef std::string t_string;
#endif
inline t_string LoadString_T(UINT uID, HINSTANCE hInstance = ::GetModuleHandle(NULL))
{
return LoadString_<t_string>(uID, hInstance);
}
cheers,
AR