提供相同的ostream和wostream流运算符的任何快捷方式

Any shortcut to providing identical ostream and wostream stream operators?

本文关键字:运算符 任何 快捷方式 wostream ostream      更新时间:2023-10-16

我想提供ostream<lt;以及wostream<lt;一个类的运算符,除了一个是宽流和另一个不是宽流之外,它们是相同的。

有没有什么比复制粘贴和进行必要的调整更丑陋的伎俩?

作为参考,这是必要的,因为我们使用wostream作为标准,但当没有提供ostream<<时,Google测试的EXPECT_PRED3无法编译,即使其他宏很乐意使用ostreamwostream

我的实际代码如下:

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

std::ostreamstd::wostream只是模板类std::basic_ostream的特殊化。编写一个模板化的operator <<将解决您的问题。这里有一个例子:

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;
}

正如评论中所指出的,您可以更进一步,通过任何公开类似流接口的类来参数化operator <<

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