mxdg
mxdg

Reputation: 314

invalid operands binary expression: ostream and std::u32string

I am trying to print out a std::u32string, but I keep getting a compilation error saying:

error: invalid operands to binary expression
  ('ostream' (aka 'basic_ostream<char>') and 'std::u32string' (aka
  'basic_string<char32_t>'))

My code consists of this:

std::u32string test = U"hello";
std::cout << test << std::endl;

Does anyone know what the proper way of printing out a u32string is? I am not interested in using a normal string or wchar strings.

Upvotes: 2

Views: 1755

Answers (1)

Brian Bi
Brian Bi

Reputation: 119194

The C++ standard library stream types are templates with the character type as the first template argument. For example, std::ostream is really std::basic_ostream<char>, as you can see from the error message. In general, you can send an std::basic_string<T> to an std::basic_ostream<T>. But std::u32string is std::basic_string<char32_t>, so the types don't match.

Unfortunately there isn't a std::u32cout of type std::basic_ostream<char32_t> or something like that, so your only choice is to convert your UTF-32 encoded string to another encoding.

The following code uses std::wstring_convert to convert the UTF-32 encoded string to UTF-8. A UTF-8 string can be directly printed to std::cout.

std::u32string test = U"hello";
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> cv;
std::cout << cv.to_bytes(test) << std::endl;

Note that codecvt isn't implemented in libstdc++ yet. I tested this code snippet using clang/libc++.

Upvotes: 1

Related Questions