fork(2) download
  1. #include <functional>
  2.  
  3. template<class Callable1, class Callable2>
  4. struct Chain : public std::unary_function<
  5. typename Callable2::argument_type,
  6. typename Callable1::result_type>
  7. {
  8. Chain(const Callable1 &f1, const Callable2 &f2) : f1(f1), f2(f2) {}
  9.  
  10. typename Callable1::result_type operator () (typename Callable2::argument_type param) { return f1(f2(param)); }
  11. private:
  12. Callable1 f1;
  13. Callable2 f2;
  14. };
  15.  
  16. template<class Callable1, class Callable2>
  17. Chain<Callable1, Callable2> chain(const Callable1 &f1, const Callable2 &f2) {
  18. return Chain<Callable1, Callable2>(f1, f2);
  19. }
  20.  
  21. #include <string>
  22. #include <iostream>
  23. #include <sstream>
  24.  
  25. using namespace std;
  26.  
  27. struct foo : public unary_function<int, double> {
  28. double m;
  29. foo(double m) : m(m) {}
  30. double operator() (int x) { return m + x; }
  31. };
  32.  
  33. struct bar : public unary_function<double, string> {
  34. string operator() (double y) {
  35. stringstream ss;
  36. ss << y;
  37. return ss.str();
  38. }
  39. };
  40.  
  41. int main() {
  42. cout << foo(0.4)(5) << endl;
  43. cout << bar()(4.5) << endl;
  44.  
  45. cout << chain(bar(), foo(3.4))(7) << endl;
  46. }
  47.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
5.4
4.5
10.4