开发者

using setw with user-defined ostream operators

开发者 https://www.devze.com 2022-12-20 02:57 出处:网络
How do I make setw or something similar (boost format?) work with my user-defined ostream operators?setw only applies to the next element pushed to the stream.

How do I make setw or something similar (boost format?) work with my user-defined ostream operators? setw only applies to the next element pushed to the stream.

For example:

cout << "    approx: " << setw(开发者_JS百科10) << myX;

where myX is of type X, and I have my own

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<<. A straightforward way to achieve this is to use an auxiliary ostringstream object:

#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() << ")";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号