std::bind()
std::bind 主要用于绑定生成目标函数,一般用于生成的回调函数,cocos的回退函数都是通过std::bind和std::function实现的。两个点要明白:
1.绑定全局或者静态函数比绑定成员函数少了个成员变量,且不需要引用如下
//绑定全局函数
auto pfunc = std::bind(func1, 3);
//绑定静态函数
pfunc = std::bind(Func::func6, 3);
//绑定类成员函数,函数前需要添加引用,多一个变量参数fuc
Func func;
pfunc =std::bind(&Func::func2,func, 3);
2.占位符std::placeholders::_1代表此处是要输入参数,且这个参数排在第一位,代码分析更明白
#include <iostream>
#include <functional>
using namespace std;
class Func
{
public:
static void func6(int numa, int numb, int numc)
{
std::cout << numa << " " << numb << " " << numc << endl;
}
void func2(int numa, int numb, int numc,std::string name)
{
std::cout << numa << " " << numb << " " << numc<<" " << name<< endl ;
}
}
void callFunc(std::function<void(int a,int b)> call)
{
call(1,2);
}
void func1(int numa, int numb, int numc)
{
std::cout << numa << " " << numb << " " << numc << endl;
}
int main()
{
callFunc(std::bind(func1, std::placeholders::_1, std::placeholders::_2, 3));
callFunc(std::bind(func1, std::placeholders::_2, std::placeholders::_1, 3));
callFunc(std::bind(func1, std::placeholders::_2, 3, std::placeholders::_1));
callFunc(std::bind(Func::func6, std::placeholders::_1, std::placeholders::_2, 3));
callFunc(std::bind(&Func::func2, func, std::placeholders::_1, std::placeholders::_2, 3, "name"));
}
运行结果如下
std::function
std::function等于函数指针,相比函数指针使用更方便,记录一下几种用法:指向全局或者静态函数,类成员函数,Lambda表达式和仿函数。指向全局函数或者静态函数时使用std::function<void()> testFunc = func3,指向类成员函数时,需要制定函数所属的类的成员变量testFunc = std::bind(&Func::func2, func, 1, 2, 3, "name")。代码如下:
#include <iostream>
#include <string>
#include <iostream>
#include <functional>
using namespace std;
class Func
{
public:
int sum;
Func()
{
sum = 2;
}
void func2(int numa, int numb, int numc,std::string name)
{
std::cout << numa << " " << numb << " " << numc<<" " << name<< endl ;
}
void func4()
{
std::cout << "func4" << endl;
}
void operator() (int a,int b)
{
std::cout << "Operator:" << sum<<" "<<a<<" "<<b<<endl;
}
static void func6(int numa, int numb, int numc)
{
std::cout << numa << " " << numb << " " << numc << endl;
}
static void func5()
{
std::cout << "static func" << endl;
}
};
void callFunc(std::function<void(int a,int b)> call)
{
call(1,2);
}
void func3()
{
std::cout <<"func3"<< endl;
}
void func1(int numa, int numb, int numc)
{
std::cout << numa << " " << numb << " " << numc << endl;
}
int main()
{
Func func;
int sum = 10;
int resultInt = 0;
//全局或者静态函数
std::cout << "全局或者静态函数" << endl;
std::function<void()> testFunc = func3;
testFunc();
testFunc = Func::func5;
testFunc();
//类成员函数
std::cout << "类成员函数" << endl;
testFunc = std::bind(&Func::func2, func, 1, 2, 3, "name");
testFunc();
//Lambda表达式
std::cout << "Lambda表达式" << endl;
testFunc = [=, &resultInt](){std::cout << sum << endl; resultInt += 100; };
testFunc();
cout << "the reslutInt is " << resultInt << endl;
//仿函数
std::cout << "仿函数" << endl;
std::function<void(int a, int b)> abFunc = func;
abFunc(10, 20);
std::cout << resultInt << std::endl;
}