std::bind()函数作为函数的适配器,它可以扩大函数是使用场合,使得函数更加灵活的被使用。
template<class F, class… Args>
bind(F&&f, Args&&… args);
参数:
f 可以是function object,函数指针,函数引用,成员函数指针,或者数据成员的指针。
返回值:
function object
placeholders 命名空间下的_1, _2, _3 指示函数参数数量和位置。
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
void func(int a, int b, int c)
{
cout << (a -b -c) << endl;
}
int main(int argc, char *argv[])
{
auto fn1 = bind(func, _1, 2, 3);
auto fn2 = bind(func, 2, _1, 3);
fn1(10);
fn2(10);
return 0;
}
运行结果:
5
-11
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
void func(int a, int b, int c)
{
cout << (a - b -c) << endl;
}
int main(int argc, char *argv[])
{
auto fn1= bind(func, _2, 2, _1);
cout << "the value of function is :";
fn1(1, 13);
auto fn2 = bind(func, _1, 2, _2);
cout << "the value of function after changing placeholder position is :";
fn2(1, 13);
return 0;
}
运行结果:
the value of function is :10
the value of function after changing placeholder position is :-14
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
void func(int a, int b, int c)
{
cout << (a - b -c) << endl;
}
int main(int argc, char *argv[])
{
auto fn1= bind(func, _1, 2, 4);
cout << "the value of function with 1 placeholder is :";
fn1(10);
auto fn2 = bind(func, _1, 2, _2);
cout << "the value of function with 2 placeholder is:";
fn2(13, 1);
auto fn3 = bind(func, _1, _3, _2);
cout << "the value of function with 3 placeholders:";
fn3(13, 1, 4);
return 0;
}
运行结果:
the value of function with 1 placeholder is :4
the value of function with 2 placeholder is:10
the value of function with 3 placeholders:8
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
class test_callback
{
public:
test_callback(void):a(10),b(100){ }
typedef function<void(int,int)> callback;
void use_value(callback func) {
cout << "value a is " << a << endl;
cout << "value b is " << b << endl;
func(a, b);
}
private:
int a;
int b;
};
class client
{
public:
client(){ this->value = 2; }
static void print_sum(int a, int b, int c) {
cout << a + b +c << endl;
}
void print_multiply(int a, int b, int c, int d) {
cout << a * b * c * d << endl;
cout << "client value is " << this->value << endl;
}
private:
int value;
};
int main(int argc, char *argv[])
{
test_callback test1;
client client1;
test1.use_value(bind(client::print_sum, _2, _1, 0));
test1.use_value(bind(&client::print_multiply, &client1, _1, _2, 2, 3));
return 0;
}
重点是在使用non static function时要加&获取nonstatic 成员函数地址。
运行结果:
value a is 10
value b is 100
110
value a is 10
value b is 100
6000
client value is 2