Search code examples
outputstreamwidestring

How to print int to std::wcerr?


How do I write the output operator<< if my object needs to print a std::wstring as well as ints, etc?

#include <iostream>

struct Foo {
  int i;
  std::wstring wstr;
};

std::ostream& operator<<(std::ostream& out, Foo const& foo) {
  out << foo.i << foo.wstr; // error                                                                                            
  return out;
}

int main() {
  Foo foo;
  std::wcerr << foo << std::endl;
}

In other words: How can I print ints and other primitive data types if I am passed a wcerr? Do I need boost::lexical_cast<std::wstring> or similar?


Solution

  • #include <iostream>
    
    struct Foo {
       int i;
       std::wstring wstr;
    };
    
    std::wostream& operator<<(std::wostream& out, Foo const& foo) {
       out << foo.i << foo.wstr;                                                                                             
       return out;
    }
    
    int main() {
       Foo foo;
       std::wcerr << foo << std::endl;
    }