boost::function と boost::bind を使えばできるとは聞いていたけど,これは面白いなー.
さらに boost::ref を使えば Closure の中から書き換えることもできるのかー.
こうなると関数リテラルを書きたくなるのが人の心といふものよ.
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
class A
{
public:
int add(int a, int b)
{
return a + b;
}
void times2(int& x)
{
x *= 2;
}
};
template<typename T> void decorate(T closure)
{
std::cout
<< "----" << std::endl
<< closure() << std::endl
<< "----" << std::endl;
}
void main()
{
A x;
boost::function<int ()> closure = boost::bind(&A::add, &x, 10, 20);
decorate(closure);
int out = 40;
boost::function<void ()> functor = boost::bind(&A::times2, &x, boost::ref(out));
functor();
std::cout << out << std::endl;
}出力結果
---- 30 ---- 80