我的应用程序中有一个生产者/消费者设计,它在用户类型上实现生产者/消费者功能。但它不能很自然地与标准库一起工作,尤其是与算法一起工作。
在 C# 中有 Enumerable 和 Observable 的概念,可以用来轻松实现这样的东西并获得很多不错的免费功能。
在 C++ 中有 ios、istream、ostream、input_iterator、output_iterator 概念,我认为它们可能有用。但在我看来,所有这些都是针对原始字符类型的,例如char、int 等...但不适用于用户类型。
当然,我可以使用真正的函数,例如 Produce/Consumer 和 std::mem_fn 用于算法。但我希望有更好的方法。
我正在寻找一些关于如何在 C++ 中针对用户类型设计 i/o 类似解决方案的最佳实践建议。
例如来自 C#
class FrameProducer : IEnumerable<Frame> // pull frames
{...}
// Some engine between
class FrameConsumer : IObserver<Frame> // push frames
{...}
我希望在 C++ 中有类似的东西,例如我认为这是不可能的。
class FrameProducer : istream<Frame> // pull frames
{...}
// Some engine between
class FrameConsumer : ostream<Frame> // push frames
{...}
也许我正在认真考虑,应该通过 KISS 进行。
想法?
最佳答案
术语是“插入运算符”和“提取运算符”,它们从流中插入和提取数据。
这是一个例子:
#include <iostream>
#include <sstream>
struct foo
{
int x;
};
// insertion operator
std::ostream& operator<<(std::ostream& s, const foo& f)
{
s << f.x; // insert a foo by inserting x
return s;
}
// extraction operator
std::istream& operator>>(std::istream& s, foo& f)
{
s >> f.x; // extract a foo by extracting x
return s;
}
int main(void)
{
std::stringstream ss;
foo f1 = {5};
ss << f1;
foo f2;
ss >> f2;
}
根据你的意愿做:
MyFrameProducer producer;
MyFrameConsumer consumer;
Frame frame; // frame should probably be in the while loop, since its
while(!producer.eof()) // lifetime doesn't need to exist outside the loop
{
producer >> frame;
consumer << frame;
}
你可能会:
struct MyFrameProducer {}; // add an eof function
struct MyFrameConsumer {};
struct Frame {};
// producer produces a frame
MyFrameProducer& operator>>(MyFrameProducer& p, Frame& f)
{
/* whatever it takes to make a frame */
return p;
}
// consumer consumes a frame
MyFrameConsumer& operator<<(MyFrameConsumer& c, const Frame& f)
{
/* whatever it takes to use a frame */
return c;
}
或者类似的东西。 (抱歉,我对这个问题的理解很浅薄。)想要这个接口(interface)有点奇怪,因为它与流无关,你最好使用不同的接口(interface)(显式方法).
关于C++ 和可枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3538806/