Any shortcut for providing the same ostream and wostream stream operators?

I want to provide ostream <and wostream <operators for a class that are identical except one is the largest and the others are not.

Is there some trickery to do this that is ugly than just copy and paste the required settings?

For reference, this is needed because we are using wostream as the standard, but Google's EXPECT_PRED3 test fails compilation when not provided ostream<<

, although 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)
  {
    ...
  }
};

      

+3


source to share


1 answer


std::ostream

and std::wostream

are just specializations of the template class std::basic_ostream

. Writing a template operator <<

should 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 the comments, you can go even further and parameterize yours with operator <<

any class that provides some kind of streaming interface:

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

      

+5


source







All Articles