简体   繁体   English

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

[英]using setw with user-defined ostream operators

How do I make setw or something similar (boost format?) work with my user-defined ostream operators? 如何设置setw或类似的东西(提升格式?)与我的用户定义的ostream操作符一起使用? setw only applies to the next element pushed to the stream. setw仅适用于推送到流的下一个元素。

For example: 例如:

cout << "    approx: " << setw(10) << myX;

where myX is of type X, and I have my own 其中myX是X型,我有自己的

ostream& operator<<(ostream& os, const X &g) {
    return os << "(" << g.a() << ", " << g.b() << ")";
}

Just make sure that all your output is sent to the stream as part of the same call to operator<< . 只需确保将所有输出作为对operator<<的同一调用的一部分发送到流中。 A straightforward way to achieve this is to use an auxiliary ostringstream object: 实现此目的的直接方法是使用辅助ostringstream对象:

#include <sstream>

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

    ostringstream oss;
    oss << "(" << g.a() << ", " << g.b() << ")";
    return os << oss.str();
}  

maybe like so using the width function: 也许是这样使用宽度函数:

ostream& operator<<(ostream& os, const X &g) {
    int w = os.width();
    return os << "(" << setw(w) << g.a() << ", " << setw(w) << g.b() << ")";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM