#include <functional>

template<class Callable1, class Callable2>
struct Chain : public std::unary_function<
    typename Callable2::argument_type, 
    typename Callable1::result_type>
{
    Chain(const Callable1 &f1, const Callable2 &f2) : f1(f1), f2(f2) {}
    
    typename Callable1::result_type operator () (typename Callable2::argument_type param) { return f1(f2(param)); }
private:
    Callable1 f1;
    Callable2 f2;
};

template<class Callable1, class Callable2>
Chain<Callable1, Callable2> chain(const Callable1 &f1, const Callable2 &f2) {
    return Chain<Callable1, Callable2>(f1, f2);
}

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

struct foo : public unary_function<int, double> {
    double m;
    foo(double m) : m(m) {}
    double operator() (int x) { return m + x; }
};

struct bar : public unary_function<double, string> {
    string operator() (double y) {
        stringstream ss;
        ss << y;
        return ss.str();
    }
};

int main() {
    cout << foo(0.4)(5) << endl;
    cout << bar()(4.5) << endl;
    
    cout << chain(bar(), foo(3.4))(7) << endl;
}
