成员函数作为回调 [英] member function as callback

查看:215
本文介绍了成员函数作为回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个实例化对象的成员函数传递给另一个函数。示例代码如下。我对任何策略开放,包括调用功能()从memberfuncpointertestclass使用类似lambda或std :: bind类似的函数。请注意,我不明白大多数线程我发现与谷歌关于lambda或std :: bind,所以请,如果可能,保持简单。还要注意,我的集群没有C + + 11,我想保持functional()简单,因为它是。谢谢!

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;
}


推荐答案

code> std :: function ,一个多态函数包装器。传递函数(...)这样的函数对象:

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;
}

然后使用 std :: bind 创建一个类型相同的函数对象,它包装了实例a的memberfuncpointertestclass :: method():

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);
}

检查此项目了解更多详情。

这篇关于成员函数作为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆