前言
一般来讲用于绑定回调的函数是地址已确定的类似全局函数或者类的成员静态函数等,如果有 特定的需求比如必须要绑定类的普通成员函数,就需要使用特别的方法,在这里推荐c++库所支持的使用一种模板函数指针funtion和bind结合使用的方法
正文
需要包含头文件#include
示例代码如下:
#include <iostream>
#include <string>
#include <functional>
typedef void(* fun_ptr )(int);
class Base
{
public:
Base() {}
void BaseCout(int v)
{
cout << __func__ << " : " << v << endl;
}
void setCallBack(fun_ptr fun,int val)
{
fun(val);
}
void setCallBack(std::function<void(int)> fun, int val)
{
fun(val);
}
void test()
{
std::function<void(int)> func_cpp11;
func_cpp11 = std::bind(&Base::BaseCout, this, std::placeholders::_1);
func_cpp11(1000);
}
};
void printf__(int val)
{
cout << __func__ << " : " << val << endl;
}
int main()
{
Base b;
std::function<void(int)> func_cpp11;
func_cpp11 = std::bind(&Base::BaseCout, &b, std::placeholders::_1);
func_cpp11(100);
b.setCallBack(func_cpp11, 1);
b.test();
}
简单说明一下 ,std::placeholders::_1表示参数占位符1 如果有多个函数输入参数,则std::placeholders::_2以此类推 ;需要注意的是,如果要用这里说的funtion表示函数指针,那么注册函数的函数形参类型也必须是funtion的类型