如何为流化自写类编写用户定义操纵符
How to write user-defined manipulators for streaming self-written class
如何在c++中编写用户定义的流操纵符来控制自编写类的流格式?
具体来说,我将如何编写简单的操作符verbose
和terse
来控制输出流的数量?
我的环境是GCC, 4.5.1及以上版本。
的例子:
class A
{
...
};
A a;
// definition of manipulators verbose and terse
cout << verbose << a << endl; // outputs a verbosely
cout << terse << a << endl; // outputs a tersely
PS:下面的只是一个附带问题,可以随意忽略它:这可以移植到接受参数的操纵符吗?Josuttis在"c++标准库"第13.6.1节末尾写道,编写带实参的操纵符依赖于实现。现在仍然是这样吗?
我不认为它们有任何理由依赖于实现。
对于实际的操纵符,我使用的是创建一个函数,该函数返回以下帮助器的实例。如果您需要存储数据,只需将其存储在helper中,一些全局变量,单例等…
/// One argument manipulators helper
template < typename ParType >
class OneArgManip
{
ParType par;
std::ostream& (*impl)(std::ostream&, const ParType&);
public:
OneArgManip(std::ostream& (*code)(std::ostream&, const ParType&), ParType p)
: par(p), impl(code) {}
// calls the implementation
void operator()(std::ostream& stream) const
{ impl(stream,par); }
// a wrapper that allows us to use the manipulator directly
friend std::ostream& operator << (std::ostream& stream,
const OneArgManip<ParType>& manip)
{ manip(stream); return stream; }
};
基于此的操纵器示例:
OneArgManip<unsigned> cursorMoveUp(unsigned c)
{ return OneArgManip<unsigned>(cursorMoveUpI,c); }
std::ostream& cursorMoveUpI(std::ostream& stream, const unsigned& c)
{ stream << " 33[" << c << "A"; return stream; }
说明:
- u使用操纵符,它返回绑定到helper 实现的helper的新实例。
- 流试图处理helper,这会调用helper上的
<<
过载 调用助手上的 - ,它使用从原始操纵符调用 传递的参数调用helper的实际实现。
()
操作符的如果你想,我可以发布2参数和3参数的帮助以及。原理是一样的
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- Visual C++(VS2017)中用户定义的转换不明确
- 使用用户定义的参数调用future/async并调用类方法
- 带有用户定义类的c++折叠表达式
- g++用户定义的动态链接库上的全局new和delete运算符
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 修改"std::set"中用户定义类型的值
- 参数包构造函数在类模板中隐藏用户定义的转换
- MAKE:找不到包含的用户定义的头文件?
- C++:用户定义的显式类型转换函数错误
- 从用户定义的类生成格式字符串?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++ 向量与用户定义的类比较?(==, <, >)
- STL 用户定义的二进制操作
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 使用宏编译时使用用户定义的数学函数,或者仅使用 c++ 中标准数学库中的函数
- C++:用户定义的类,以成员字段作为地址