functionとbindの組み合わせ

東方算程譚 - delegateもどき


functionとbindを組み合わせて使うとなかなかおもしろいことができる

#include <iostream>
#include <boost/tr1/functional.hpp> // C++0xでは<functional>

using namespace std;
using namespace std::tr1;

int add(int lhs, int rhs)
{
    return lhs + rhs;
}

int main()
{
    function<int(int)> f = bind(add, _1, 3); // addの第二引数を3に固定する

    cout << f(2) << endl; // add(2, 3);

    return 0;
}

bindを使って引数を束縛することで「同じ引数は二度と書かない」ということができる



また、メンバ関数(インスタンスメンバ)にも同様のことができる

#include <iostream>
#include <boost/tr1/functional.hpp>

using namespace std;
using namespace std::tr1;

struct hoge {
    int add(int lhs, int rhs)
    {
        return lhs + rhs;
    }
};

int main()
{
    hoge h;

    function<int(int)> f1 = bind(&hoge::add, &h, _1, 3);
    cout << f1(2) << endl; // (&h)->add(2, 3);

    function<int(int)> f2 = bind(&hoge::add, h, _1, 3);
    cout << f2(2) << endl; // h.add(2, 3);

    return 0;
}

funtionはちょっと前に作ったから、今度はbind作ろう


...と思ったらid:melt_slincさんに先を越された



それでも作るけど