member function as callback

六月ゝ 毕业季﹏ 提交于 2019-12-11 08:26:12

问题


I would like to pass a member function of an instantiated object to another function. Example code is below. I am open for any strategy that works, including calling functional() from another function inside memberfuncpointertestclass using something like lambda or std::bind. Please note that I did not understand most of the threads I found with google about lambda or std::bind, so please, if possible, keep it simple. Also note that my cluster does not have C++ 11 and I would like to keep functional() as simple as it is. Thank you!

int functional( int (*testmem)(int arg) )
{
    int a = 4;
    int b = testmem(a);
    return b;
}

class memberfuncpointertestclass
{
public:
    int parm;
    int member( int arg )
    {
        return(arg + parm);
    }
};

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    int (*testf)(int) = &a.member;

    std::cout << functional(testf);
}

int main()
{
    funcpointertest();
    return 0;
}

回答1:


You cannot invoke a method on an object without an instance to refer to. So, you need to pass in both the instance as well as the method you want to invoke.

Try changing functional to:

template <typename T, typename M>
int functional(T *obj, M method)
{
    int a = 4;
    int b = (obj->*(method))(a);
    return b;
}

And your funcpointertest to:

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    std::cout << functional(&a, &memberfuncpointertestclass::member);
}



回答2:


This is a job for std::function, a polymorphic function wrapper. Pass to functional(...) such a function object:

#include <functional>

typedef std::tr1::function<int(int)> CallbackFunction;

int functional(CallbackFunction testmem)
{
    int a = 4;
    int b = testmem(a);
    return b;
}

then use std::bind to create a function object of the same type that wraps memberfuncpointertestclass::method() of instance a:

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    CallbackFunction testf = std::bind(&memberfuncpointertestclass::member, &a, std::placeholders::_1);

    std::cout << functional(testf);
}

Check this item for more details.



来源:https://stackoverflow.com/questions/16045892/member-function-as-callback

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!