将函数和成员函数作为参数传递给另一个函数

时间:2015-10-12 15:22:08

标签: c++

我编写了一个库,允许通过检查接收的ASCII字符将函数绑定到键事件。它适用于主代码中定义的非成员函数。它不适用于成员函数。我知道这是因为成员函数和非成员函数属于不同类型。如何在我的库中将以前未定义的类的函数传递给此函数?

定义类型:

typedef void (*tobind)();

有问题的功能:

void Keybinder::bind(char key,int mode,tobind func) {
switch(mode){
    //execute depending on the event mode argument
    case 0:
        pressed[key] = func; //assign the function to the character pressed event
        break;
    case 1:
        down[key] = func; //assing the function to the character down event
        break;
    case 2:
        released[key] = func; //assign the function to the character released event
        break;
}
}

4 个答案:

答案 0 :(得分:1)

如果您使用的是支持C ++ 11语法的编译器,那么我建议使用std::functionstd::bind方法。

你的typedef看起来像这样:

typedef std::function<void()> tobind;

你会像这样使用std :: bind:

auto func = std::bind(&Foo, arg1, arg2); // non-member usage
auto memFunc = std::bind(&A::MemberFoo, aInstance, arg1, arg2); // member-function usage

答案 1 :(得分:0)

使用转发去除 + std::bind

template <class F, class... Args>
    void Keybinder::bind(char key,int mode,F&& f,Args&&... args){
    std::function<void()> callback = std::bind(std::forward<F>(f),std::forward<Args>(args)...);
    //use callback as original func
 }

请注意,非静态成员函数需要传递它们的this指针。

struct Foo{
  void func(){};
};

Foo f;
keybinder.bind('a',4,&Foo::func,&f);

答案 2 :(得分:0)

  

如何在我的库中将以前未定义的类的函数传递给此函数?

您不能使用Keybinder::bind的现有界面。

答案 3 :(得分:0)

fwiw,一个有点难看的中间解决方案 - 如果你的库的绑定方法允许它 - 是绑定到WTC static函数,并将特定实例作为引用/指针传递(在任何'用户数据'你的库允许回调)。 class函数可以充当static引用的实例,从而访问其成员,就像它们自己的一样。

然而,你基本上会回到C风格的'OOP',所以如果你有更好的替代方案,这不是一个非常优雅的方式。

我将假设在我使用此模式时,我使用的库不支持任何更好的方式。乙 - )