c++stlgoogletestvisual-c++-2013

Any shortcut to providing identical ostream and wostream stream operators?


I want to provide ostream<< and wostream<< operators for a class, which are identical other than one being widestream and the other not.

Is there some trickery to do this which is ugly than just copy-pasting and making the necessary tweaks?

For reference, this is necessary because we use wostream as standard, but Google-test's EXPECT_PRED3 fails compilation when no ostream<< is provided, even though other macros happily work with ostream or wostream.

My actual code looks like this:

class MyClass
{
...
public:
  friend std::wostream& operator<<(std::wostream& s, const MyClass& o)
  {
    ...
  }
};

Solution

  • std::ostream and std::wostream are just specializations of a template class std::basic_ostream. Writing a templated operator << shall solve your problem. Here's an example:

    struct X { int i; };
    
    template <typename Char, typename Traits>
    std::basic_ostream<Char, Traits> & operator << (std::basic_ostream<Char, Traits> & out, X const & x)
    {
        return out << "This is X: " << x.i << std::endl;
    }
    

    As pointed out in comments, you can go even further and parametrize your operator << by any class that exposes some stream-like interface:

    template <typename OStream>
    OStream & operator << (OStream & out, X const & x)
    {
        return out << "This is X: " << x.i << std::endl;
    }