I just wanted to share this technique for piping the cout from one function
to the cin of another, using the pipe operator:
#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);
}
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;
}
Any comments or suggestions?
I am working on a version which allows passing of arguments to functions,
and which allows arbitrary chaining.
--
Christopher Diggins
http://www.cdiggins.com
http://www.heron-language.com