如何用 C++ 编写自定义流转换?

Jak*_*old 5 c++ stream stream-processing c++03 c++98

在大量使用 Haskell 和函数式语言之后,我开始学习 C++,我发现我一直在尝试解决同样的问题:

  • 从输入流中读取一些数据
  • 根据特定算法对它们进行标记
  • 处理令牌

如果这是 Haskell,我可以简单地利用一切都是懒惰的事实,并在我想到的时候编写我的转换,然后它会在下游被消耗时应用。甚至有一些库可以执行这种精确的模式(导管管道)。

假设我想获取序列1 2 3 4 5 6 ...和输出12 34 56 ...。我可以了解如何编写在流上运行并就地处理数据的临时代码。但我想知道是否存在一种抽象机制,允许我通过转换来自另一个流的数据(以任何可以想到的方式)来构建新的流。这种抽象应该允许我在处理数据时缓冲数据,而不仅仅是单个元素到新值的简单映射。

以下是限制:

  • 除了 stdlib 之外,我无法使用任何其他库。
  • 它必须适用于 C++03(意味着没有 C++11 功能。)

如果你在想,这是作业吗?好吧,我收到了很多类作业,这些作业要求我处理数据流(这就是没有库和 C++03 限制的原因)。并不是我不知道如何使用while循环来做到这一点,而是我想知道 stl 中是否存在现有的流抽象,只是等待被发现和使用。

但如果唯一的方法是使用 C++11,那么我想知道。

Sur*_*urt 2

概念代码,未经测试。想象一下有很多错误检查和正确的语法。

struct add : public std::binary_function<int,int,int> {
  int operator() (int a, int b) {return (a + b);}
};

template<typename inType, typename dType, typename outType, class binFunc>
outType Transformer(inType& inStream, outType& outStream, binFunc func) {
  dType a, b;
  // Read some data from an input stream
  // Tokenize them based on a specific algorithm
  inStream>> a >> b; 
  //outStream << func(a, b);
  return func(a,b); // Process the tokens
}

int main() {
  std::ifstream in("input.dat", std::ifstream::in); // , std::ios::binary
  std::ofstream out("output.dat");
  struct add adder;  // to Process the tokens

  out << Transformer(in, out, adder);

  return exit_success;
}
Run Code Online (Sandbox Code Playgroud)