简体   繁体   中英

How to compose stream operations in C++?

For a certain program, I have two functions that take an input and an output stream, doing some operation on the input and writing to the output. I can call them like this:

a(cin, cout);
b(cin, cout);

Say I want to run them in sequence, so that both the operations from a and b are applied. Currently, I'm using a stringstream as an intermediate iostream to store the result, like so:

stringstream buffer;
a(cin, buffer);
b(buffer, cout);

However, this pretty much negates the use of streams as all the data remains in memory for the intermediate step, even though both operations can be applied to streams with constant memory.

Is there a (standard) technique I can use to combine these operations, preferably without changing a and b too much? Also, if possible, I'd like to avoid boost.

Note: the functions here are just for example purposes. In the actual program both are methods on two objects.

Is there a (standard) technique I can use to combine these operations, preferably without changing a and b too much? Also, if possible, I'd like to avoid boost.

What you really want is some sort of producer/consumer idiom where the producer reads from IN and the consumer writes to OUT. As far as I am aware, nothing in native C++ will help, although Boost has support for coroutines which is (to my knowledge) basically what you'll end up with.

Here's a way to implement your program that may allow you to make minimal changes to a and b . In this case, I assume you're reading a line-deliminated text file. If you're reading binary files, you'll want to read a fixed number of bytes, not a line.)

std::stringstream buffer;
std::string line;
while (std::getline(std::cin, line))
{
  std::istringstream iss(line);
  a(iss, buffer);
  b(buffer, std::cout);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM