How do I add to a wstring?
This works with std::string
std::string class::something(char* input) {
std::string s(input);
s = "hai! " + s;
return s;
}
But fails if I try the same thing w开发者_JAVA百科ith wstring
std::wstring class::something(wchar_t* input) {
std::wstring s(input);
s = "hai! " + s;
return s;
}
How do I do the same thing with std::wstring?
The problem here is types. A wstring isn't a string, but a quoted string constant is related to it (it is generally a const char*
), so
s = "hai! " + s;
is actually a problem.
The value "hai! "
is of type const char*
, not type const wchar_t*
. Since const char*
is a basic type, it's searching for a global operator+
that operates const char*
and wstring
, which doesn't exist. It would find one for const wchar_t*
and wstring
, because std::basic_string<T>
, the template underyling type for both string
and wstring
(using char
and wchar_t
as the type parameter, respectively) also creates template methods for operator+ (const T*& s1, const basic_string<T> s2)
so that addition can work.
Therefore, you need to make "hai! " a wstring:
std::wstring class::something(wchar_t* input){
std::wstring s(input);
s = L"hai! " + s;
return s;
}
The L
prefix on a string constant, in Visual C++, defines it to be "long", and therefore a wstring. wstring
is actually basic_string<wchar_t>
, which is, because of the behavior of C++ templates, a completely different type from basic_string<char>
(a std::string
), so you can't combine the two.
You use a wide character literal instead of a char character literal by prefixing "hai!" with L.
Instead of having 2 versions of the code (1 for wide and 1 for multi-byte):
#ifdef _UNICODE
typedef std::wstring tstring;
typedef wchar_t tchar;
# define TEXT(s) L##s
#else
typedef std::string tstring;
typedef char tchar;
# define TEXT(s) s
#endif
tstring class::something(tchar* input)
{
tstring s(input);
s = TEXT("hai! ") + s;
return s;
}
This prevents having to rewriting code when you change your compiler string encoding compiler options.
精彩评论