#include <iostream>
#include <string>
using namespace std;
int main()
{
wcout << L"Hello"; // OK.
wcout << wstring(L"Hello"); // OK.
wcout << "Hello"; // OK. Why?
wcout << string("Hello"); // Error. Why?
}
Why does std::wcout accept a narrow string literal as its argument but doesn’t accept a narrow string object?
This is dictated by § 27.7.3.6.4 of the C++11 Standard, where the following two overloaded operators (among others) are specified:
The last overload deals explicitly with
char-based C-strings. This means that even for instantiations of thebasic_ostream<>class template with the argumentwchar_tthere will be one overload which will deal with narrowcharstrings.Moreover, per § 27.7.3.6.4/5:
On the other hand, the statement
wcout << string("Hello");does not compile becausestringdoes not have an implicit conversion toconst char*, and because there is no overload ofoperator <<that would insert astringbuilt with one character type into an output stream with a different underlying character type.In Standard terms (see § 21.4.8.9), here is how the definition of the overloaded
operator <<looks like forstd::string:As you can see, the same template parameter
charTis used to instantiate bothbasic_ostreamandbasic_string.