我需要实现一个 C++ iostream 操纵器。在这里和那里阅读似乎人们使用两种方式
使用
ios_base::xalloc
和ios_base::iword
从 iostream 实现派生类,如下例所示。
我喜欢第二种方式,但与第一种方式相比,它可能有我看不到或无法理解的缺点。
// Example of point 2
struct mystream : public iostream
{
ostream& o_;
mystream(ostream& o) : o_(o) {}
ostream& operator << (int a) {
// do something with o and a
o << "<A>" << a << "</A>";
return *this;
}
};
ostream mymanipulator(ostream& out) {
return mystream(out);
}
我在C++ iostream 的自定义操纵器这篇文章中找到了方法 #2 的一个非常好的实现。
在我看来,它xalloc and iword
更习惯于为我的自定义流存储一些自定义内部状态,以便在某个时候使用。