我需要实现一个 C++ iostream 操纵器。在这里和那里阅读似乎人们使用 2 种方式
使用
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);
}
我在这篇文章 Custom manipulator for C++ iostream 中找到了方法 #2 的一个很好的实现.
在我看来,xalloc 和 iword
更多地用于存储一些自定义内部状态,以便我的自定义流在某个时候使用。
最佳答案
我不会推荐这些东西。
Using
ios_base::xalloc
andios_base::iword
您还没有确切地告诉我们您将如何使用存储在流中的数据,但是设置 iword()
有点不直观。每一次你想写的时候。
Implementing a derived class from
iostream
...
通常您不想从流基类继承。它可能有用的唯一情况是当您将自定义流包装在流缓冲区周围时,但这通常是为了方便。
另一个问题是您的插入器返回 std::ostream
,这意味着当链接运算符时,您只会写入 std::ostream
第二次写入时的基础对象:
mystream str;
str << 100 // writes "<A>100</A>"
<< 200; // only writes 200
惯用的解决方案是定制一个 std::num_put<char>
您的流语言环境的方面。通过这种方式,您可以将功能直接包装在流的幕后,这样就不会改变用户使用流的方式。
关于c++ - 通过 xalloc/iword 或通过派生类的 iostream 操纵器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23933655/