Foo
のメソッドがコンストラクターに渡され、Bar
後で特定のBar
オブジェクトで呼び出される例を次に示します。
struct Foo
{
int z;
int add(int x, int y)
{
return x + y + z;
}
int mul(int x, int y)
{
return x * y * z;
}
};
typedef int (Foo::*foo_method)(int, int);
struct Bar
{
foo_method m;
Bar(foo_method m) : m(m) {}
int call_on(Foo* foo)
{
return (foo->*m)(4, 2);
}
};
int main()
{
Bar bar(&Foo::add);
Foo foo = { 123 };
bar.call_on(&foo);
}
一方、構築時にFoo
オブジェクトをすでに知っている場合は、メソッドがどのクラスに属しているかは実際には気にしません。必要なのは後で呼び出すファンクターだけで、オブジェクトはクライアントによって簡単にバインドできます。Bar
Bar
Foo
#include <functional>
struct Bar
{
std::function<int (int, int)> f;
Bar(std::function<int (int, int)> f) : f(f) {}
int call()
{
return f(4, 2);
}
};
using namespace std::placeholders;
int main()
{
Foo foo = { 123 };
Bar bar(std::bind(&Foo::add, &foo, _1, _2));
bar.call();
}
C ++ 0xコンパイラがない場合は、またはに置き換えてstd::bind
ください。std::tr1::bind
boost::bind