Boost Cookbook - Function composition
理解するのに時間がかかった・・・
まだfunction + bind, lambdaの組み合わせには慣れないな
#include <iostream> #include <boost/function.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> using namespace std; using namespace boost; using namespace boost::lambda; template <class R, class I, class S> function<R(I)> compose(function<R(I)> f, function<I(S)> g) { return bind(f, bind(g, _1)); } template <class T, class Y> function<T> operator*(function<T> f, function<Y> g) { return compose(f, g); } int main() { function<int(int)> inc(_1 + 1); function<int(int)> triple(_1 * 3); function<int(int)> square(_1 * _1); cout << (inc * triple)(2) << " = 2 x 3 + 1" << endl; // 7 cout << (square * square)(3) << " = (3x3) x (3x3)" << endl; // 81 return 0; }