将setw与用户定义的ostream运算符一起使用

Nei*_*l G 5 c++ boost stream

如何设置setw或类似的东西(提升格式?)与我的用户定义的ostream操作符一起使用?setw仅适用于推送到流的下一个元素.

例如:

cout << "    approx: " << setw(10) << myX;
Run Code Online (Sandbox Code Playgroud)

其中myX是X型,我有自己的

ostream& operator<<(ostream& os, const X &g) {
    return os << "(" << g.a() << ", " << g.b() << ")";
}
Run Code Online (Sandbox Code Playgroud)

Man*_*uel 7

只需确保将所有输出作为同一调用的一部分发送到流中operator<<.实现此目的的直接方法是使用辅助ostringstream对象:

#include <sstream>

ostream& operator<<(ostream& os, const X & g) {

    ostringstream oss;
    oss << "(" << g.a() << ", " << g.b() << ")";
    return os << oss.str();
}  
Run Code Online (Sandbox Code Playgroud)