首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++和Enumerable

C++和Enumerable
EN

Stack Overflow用户
提问于 2010-08-22 04:18:09
回答 2查看 1.4K关注 0票数 1

我在我的应用程序中有一个生产者/消费者设计,它实现了对用户类型的生产/消费功能。但对于标准库,尤其是算法,它不能很自然地工作。

在C#中,有可枚举和可观察的概念,可以用来轻松地实现这样的东西,并获得许多很好的免费功能。

在C++中有ios,istream,ostream,input_iterator,output_iterator的概念,我认为这些概念可能会很有用。但在我看来,所有这些都是针对原始字符类型的,例如char、int等。而不是针对用户类型。

当然,我可以使用真实的函数,比如Produce/Consumer和std::mem_fn来实现算法。但我希望有更好的方法。

我正在寻找一些关于如何在C++中针对用户类型设计i/o类似解决方案的最佳实践建议。

例如来自C#

代码语言:javascript
复制
class FrameProducer : IEnumerable<Frame> // pull frames
{...}

// Some engine between

class FrameConsumer : IObserver<Frame> // push frames
{...}

我希望在C++中有类似的东西,例如,我不相信这是可能的。

代码语言:javascript
复制
class FrameProducer : istream<Frame> // pull frames
{...}

// Some engine between

class FrameConsumer : ostream<Frame> // push frames
{...}

也许我想得太多了,应该通过亲吻来实现。

有什么想法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-22 04:36:29

这两个术语是“插入运算符”和“提取运算符”,它们从流中插入和提取数据。

下面是一个例子:

代码语言:javascript
复制
#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;
}

根据你想做的事情:

代码语言:javascript
复制
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;
} 

您可能会这样做:

代码语言:javascript
复制
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;
}

或者类似的东西。(对不起,我对这个问题的理解很少。)想要这个接口有点奇怪,因为它与流无关,而且您可能更适合使用不同的接口(显式方法)。

票数 3
EN

Stack Overflow用户

发布于 2010-08-22 04:37:40

看看this生产者/消费者解决方案。虽然它是纯C语言写的,但它太优雅了,所以我还是忍不住要把它贴出来。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3538806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档