Boost logo

Boost :

From: christopher diggins (cdiggins_at_[hidden])
Date: 2005-01-08 14:24:51


Thank you very much to everyone who has been helping me out, and have made
some suggestions. It took me a bit to realize the implications of what some
people were suggesting, so I apologize if I am a bit slow to catch up.

I now have code which allows two arbitrary functions ( which have no
parameters and return void ) to be chained together from cout of one to the
cin of the other:

void HelloWorld() {
  cout << "hello world" << endl;
}

void CountChars() {
  string s;
  s = cin.getline();
  cout << static_cast<int>(s.size()) << endl;
}

int main() {
  filter(HelloWorld) | filter(CountChars);
  return 0;
}

This is done by redirecting cout for the first function to a temporary
stringstream buffer, and then redirecting the output of the second stream.
The code to accomplish this is trivial, but potentially interesting for the
community:

#include <iostream>
#include <sstream>

using namespace std;

typedef void(*procedure)();

class filter {
  public:
    filter(procedure x) : proc(x) { }
    void operator()(istream& in, ostream& out) {
      streambuf* inbuf = cin.rdbuf();
      streambuf* outbuf = cout.rdbuf();
      cin.rdbuf(in.rdbuf());
      cout.rdbuf(out.rdbuf());
      proc();
      cin.rdbuf(inbuf);
      cout.rdbuf(outbuf);
    }
  private:
    procedure proc;
};

void operator|(filter f1, filter f2) {
  stringstream s;
  f1(cin, s);
  s.seekg(0);
  f2(s, cout);
}

Many good suggestions have been made so far. Some possibilities for more
features are:

1) create wrapper objects around the filters, this would allow the passing
of data to functions, like a command line string
2) chain arbitrarily long sequences by creating a pipeline object, and doing
the piping in its destructor
3) allow the chaining of streams
4) allow the chaining of the various iostreams concepts
5) allow the chaining of FILE* (i.e. popen, etc.)
6) allow the chaining of processes
7) allow threading of functions

Any comments or suggestions? Is this a direction people would like to see
continued? Also is anyone interested in collaborating?

Christopher Diggins
http://www.cdiggins.com
http://www.heron-language.com


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk