将函数和成员函数作为参数传递给另一个函数
Passing functions and member functions as an argument to another function
我编写了一个库,允许通过检查接收到的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;
}
}
如果你正在使用支持c++ 11语法的编译器,那么我建议使用std::function和std::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
如何将先前未定义的类的函数传递给库中的此函数?
您不能使用Keybinder::bind
的现有接口。
fwiw,一个有点难看的中间解决方案-如果你的库的绑定方法允许的话-是绑定到static
class
函数,并将特定的实例作为引用/指针传递(在你的库允许回调的任何"用户数据"中)。static
函数能够作为引用实例的friend
,从而访问它们的成员,几乎就像它们是自己的一样。
然而,你基本上回到了旧的c风格的'OOP',所以这不是一个非常优雅的方式,如果你有更整洁的替代方案。
我将假设在我使用这种模式的时候,我使用的库不支持任何更好的方式。B -)
use forward declaration + 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);
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 为什么我不能将引用作为 std::async 的函数参数传递
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何通过 C++ 中的函数参数传递初始值设定项列表的固定大小的初始值设定项列表?
- 我可以动态创建新地图并作为函数参数传递吗?
- 将任意模板向量作为函数参数C++传递
- 将函数指针作为函数参数传递的目的
- C++:通过函数参数传递的值给出不同的结果
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 通过宏将函数参数传递给函数
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将派生类作为函数参数传递:如果派生类成员不在父类中怎么办
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称