4

我想为一个类提供 ostream<< 和 wostream<< 运算符,除了一个是widestream 而另一个不是之外,它们是相同的。

是否有一些技巧可以做到这一点,而不仅仅是复制粘贴和进行必要的调整?

作为参考,这是必要的,因为我们使用 wostream 作为标准,但是当提供 no 时,Google-test 的 EXPECT_PRED3 编译失败ostream<<,即使其他宏可以愉快地使用ostreamor wostream

我的实际代码如下所示:

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

1 回答 1

6

std::ostream并且std::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;
}
于 2014-09-17T15:26:46.490 回答