I often find that I need to pass a non-static method as a call-back
instead of a functor or a function. The problem with that is the
implicit 'this' parameter. So I created an adaptor that given an
object and a unary method creates a unary_function-defived functor
bound to that object and method. Code is below.
// Method-to-functor adapter
template<class TClass, typename TArg, typename TRet>
class unary_method : public unary_function<TArg, TRet>
{
public:
unary_method(TClass& object,
TRet (TClass::*method)(TArg)) :
_object(object),
_method(method)
{}
TRet operator()(TArg arg) {
(_object.*_method)(arg);
}
private:
TClass& _object;
TRet (TClass::*_method)(TArg);
};
Questions:
Is this the best (simplest, most efficient) way to do it?
Isn't this a common enough problem for the solution to be available? I
searched, but found nothing in stl, boost or anywhere else.
Here's a test driver, in case you want to give it a try:
<code>
#include <iostream>
#include <functional>
using namespace std;
// Method-to-functor adapter
template<class TClass, typename TArg, typename TRet>
class unary_method : public unary_function<TArg, TRet>
{
public:
unary_method(TClass& object,
TRet (TClass::*method)(TArg)) :
_object(object),
_method(method)
{}
TRet operator()(TArg arg) {
(_object.*_method)(arg);
}
private:
TClass& _object;
TRet (TClass::*_method)(TArg);
};
class MyClass
{
public:
void MyMethod(int a) {
cout << a << endl;
};
static void MyStaticMethod(int a) {
cout << a << endl;
};
};
main () {
void (*foo)(int) = &MyClass::MyStaticMethod;
foo(3);
MyClass my_object;
unary_method<MyClass, int, voidbar(my_object,
&MyClass::MyMethod);
bar(5);
}
</code>
Regards,
Zori