I’m working on converting an MFC program from MBCS to Unicode. I’ve found that the insertion operator << is working differently with CStringA than with CStringW instances.
// char
std::ostringstream c_oss;
CStringA c_s("Hello");
c_oss << c_s;
TRACE("%s\n", c_oss.str().c_str());
// wchar_t
std::wostringstream w_oss;
CStringW w_s(L"World");
w_oss << w_s;
TRACE(L"%s\n", w_oss.str().c_str());
I would expect this to print “Hello\nWorld\n” but instead it prints “Hello\n14,5E6,B38\n”. That is, it’s printing the address of the w_s data rather than the data.
If I debug into w_oss << w_s, I can see that the overload for inserting a const void* is being selected rather than the one for inserting a const wchar_t*. It’s working correctly for the char version. If I explicitly apply the case (LPCTSTR) or (const wchar_t*), it works correctly for the wchar_t version.
Any ideas why the wchar_t version is working differently than the char version?
The wide character version of
operator<<is a template and as such requires an exact argument match. No user-defined conversion, such asCStringW::operator wchar_t*()is implicitly performed.OTOH the
void*version of the same operator is not a template and happily uses the user-defined conversion operator.