C++11:std::bind实现参数动态绑定


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/wwwroot/fawdlstty.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/wwwroot/fawdlstty.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383

参数动态绑定在实际编程中用的不多,但在特定情况下非常有用。这个功能的意思是,将函数与参数绑定,下次调用时可以不用再次麻烦的传递参数。首先给出一个示例:

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,所以在实际调用时不用再次赋值。注意函数对象的声明。
继续阅读C++11:std::bind实现参数动态绑定