【发布时间】:2011-04-28 09:37:32
【问题描述】:
如何在 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 在接近 13.6.1 节末尾的“C++ 标准库”中写道,编写带参数的操纵器取决于实现。这仍然是真的吗?
【问题讨论】:
-
不是重复的,而是一个相关(有趣)的主题:How do the stream manipulators work?