gpt4 book ai didi

c++ - 在 C++ 中是否有缓冲输出操作的标准解决方案?

转载 作者:搜寻专家 更新时间:2023-10-31 01:20:18 24 4
gpt4 key购买 nike

我编写了这个为一般输出操作提供缓冲的简单类:

template <typename T>
class WriteBuffer {
typedef void (&flush_t)(const T* values, const size_t size);

public:
WriteBuffer(size_t size, flush_t flush) : flush_(flush) {
v_.reserve(size);
}

~WriteBuffer() { flush(); }

void flush() {
if (v_.size() > 0) {
flush_(&v_[0], v_.size());
v_.clear();
}
}

void write(const T value) {
if (v_.size() == v_.capacity())
flush();
v_.push_back(value);
}

private:
vector<T> v_;
flush_t flush_;
};

(为简单起见省略了错误检查。)以下示例程序:

void writeInt(const int* values, const size_t size) {
cout << "Writing buffer of size " << size << ": " << endl;
for (size_t i = 0; i < size; ++i)
cout << values[i] << ", ";
cout << endl;
}

int main(int argc, char* argv[]) {
WriteBuffer<int> buffer(5, writeInt);

for (size_t i = 0; i < 18; ++i)
buffer.write(i);

return 0;
}

然后生成以下输出:

Writing buffer of size 5: 0, 1, 2, 3, 4,Writing buffer of size 5: 5, 6, 7, 8, 9,Writing buffer of size 5: 10, 11, 12, 13, 14,Writing buffer of size 3: 15, 16, 17,

Is there any standard/better solution of this problem, e.g. some STL container / BOOST class with similar capabilities? Thanks!

Additional question: Would you prefer using function object instead of function reference flush_t?

EDIT

I would like to use such buffering for any type T and any flush operation provided by the client (not only characters and output streams). For example:

template <typename T>
void write(const T* values, const size_t size) {
...
H5Dwrite(..., values);
...
}

WriteBuffer<unsigned long> buffer(8192, write<unsigned long>);

将数据写入 HDF5 数据集。 (这里不解决 HDF5 数据类型。)

最佳答案

标准解决方案是子类std::streambuf ,这正是为您的任务而设计的。有一些 boost magic以简化实现。

关于c++ - 在 C++ 中是否有缓冲输出操作的标准解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5030387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com