参数动态绑定在实际编程中用的不多,但在特定情况下非常有用。这个功能的意思是,将函数与参数绑定,下次调用时可以不用再次麻烦的传递参数。首先给出一个示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> #include <functional> using namespace std; void func (int i, int j) { cout < < "i = " << i << ", j = " << j << endl; } int main(int argc, char* argv[]) { function<void (int, int)> f = func; f (1, 2); return 0; }</functional></string></iostream> |
结果为i = 1, j = 2
以上例子是使用函数对象保存函数地址,然后调用函数对象的示例代码,下面我让函数对象f与参数进行绑定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> #include <functional> using namespace std; void func (int i, int j) { cout < < "i = " << i << ", j = " << j << endl; } int main(int argc, char* argv[]) { function<void ()> f = bind(func, 1, 2); f (); return 0; }</functional></string></iostream> |
结果为i = 1, j = 2
由于已经绑定了参数1和2,所以在实际调用时不用再次赋值。注意函数对象的声明。
对于已经绑定参数的函数对象,传递参数会发生什么奇怪的事情呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> #include <functional> using namespace std; void func (int i, int j) { cout << "i = " << i << ", j = " << j << endl; } int main(int argc, char* argv[]) { function<void (int, int)> f = bind(func, 1, 2); f (3, 4); return 0; } |
结果为i = 1, j = 2
以上代码是给已经绑定参数的函数对象进行传参,然而并没什么卵用,结果还是同上。那么我想绑定部分参数,调用时再传递部分参数,该怎么实现呢?比如绑定第一个参数,然后调用时只使用第二个参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> #include <functional> using namespace std; void func (int i, int j) { cout << "i = " << i << ", j = " << j << endl; } int main(int argc, char* argv[]) { function<void (int, int)> f = bind(func, 1, placeholders::_2); f (3, 4); return 0; } |
结果为i = 1, j = 4
这儿用了一个placeholders::_2,简单的理解就是一个占位符,用于接收用户传递的第二个参数。同理,用户传递第一个参数的占位符为placeholders::_1。下面再来一个示例,交换传入的参数顺序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> #include <functional> using namespace std; void func (int i, int j) { cout << "i = " << i << ", j = " << j << endl; } int main(int argc, char* argv[]) { function<void (int, int)> f = bind (func, placeholders::_2, placeholders::_1); f (1, 2); return 0; } |
结果为i = 2, j = 1
上面代码的意思是,获取用户调用的第二个参数,将其第一个传入,然后获取用户调用的第一个参数,将其第二个传入。于是,参数1和参数2的顺序就反过来了
有什么用?
小程序几乎用不到,一般在大型程序里面用,在不修改其他模块代码的情况下对参数进行修改。比如同一个回调接口需要调用不同参数数量的回调函数,那么可以通过这个绑定对回调函数进行封装,兼容回调接口;另外不是在特定场合只能用这个,这个只是一种可行的解决方案