提供相同的ostream和wostream流运算符的任何快捷方式
Any shortcut to providing identical ostream and wostream stream operators?
我想提供ostream<lt;以及wostream<lt;一个类的运算符,除了一个是宽流和另一个不是宽流之外,它们是相同的。
有没有什么比复制粘贴和进行必要的调整更丑陋的伎俩?
作为参考,这是必要的,因为我们使用wostream作为标准,但当没有提供ostream<<
时,Google测试的EXPECT_PRED3无法编译,即使其他宏很乐意使用ostream
或wostream
。
我的实际代码如下:
class MyClass
{
...
public:
friend std::wostream& operator<<(std::wostream& s, const MyClass& o)
{
...
}
};
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;
}
相关文章:
- ::(范围解析运算符)前面没有任何东西
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- 矩阵在任何运算符之后都变得相同
- 使用模板运算符 () 对任何函子的提升函数
- CPP 中的 ++ 运算符对字符是否有任何重载?
- 为运算符编写模板<<适用于任何向量
- 任何机构都可以在运算符重载中解释这行代码
- 如何确保 "<<" 运算符适用于模板化 ADT 定义中的任何泛型类型?
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- C++功能运算符结构不执行任何操作
- 错误的任何修复:二进制">>"找不到运算符
- 为什么赋值运算符必须返回任何内容
- 在指向类类型的指针中,有没有任何方法可以用outusing*调用类运算符
- 在任何编程语言中,递增和递减运算符的功能是什么?
- 在函数中打印全局变量而不是 :: 运算符的任何替代方法
- 什么不能接受字符串向量并用 offest 和 assigmnet 运算符替换任何字符串的字符?
- 重载运算符:常量与非常量返回类型:任何性能差异
- 将运算符类型转换为除某些引用之外的任何算术类型
- 为什么显式运算符 bool 允许我转换为任何基元类型
- 这里有任何方法可以使用拉普拉斯运算符来确定图像是否模糊