1. 绑定普通函数
1.1. 普通调用
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <set> #include <iostream> #include <functional> using namespace std; void f(int n1, int n2) { std::cout << n1 << ' ' << n2 << '\n'; }
int main() { int n = 7; auto f1 = std::bind(f, 1, 2); f1(); }
|
1.2. 参数排序传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <set> #include <iostream> #include <functional> using namespace std; void f(int n1, int n2, int n3, const int& n4, int n5) { std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n'; }
int main() { int n = 7; auto f1 = std::bind(f, std::placeholders::_2, 42, std::placeholders::_1, std::cref(n), n); n = 10; f1(1, 2, 1001); }
|
2. 绑定成员函数
注意:调用指向非静态成员函数指针或指向非静态数据成员指针时,首个实参必须是引用或指针(可以包含智能指针,如 shared_ptr
、unique_ptr
),指向要访问其成员的对象。
2.1. 绑定成员函数指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <set> #include <iostream> #include <functional>
using namespace std; struct Foo { void print_sum(int n1, int n2) { std::cout << n1 + n2 << '\n'; } int data = 10; };
int main(){ Foo foo; auto f3 = bind(&Foo::print_sum, &foo, 95, std::placeholders::_1); f3(5); }
|
2.2. 绑定成员对象指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <set> #include <iostream> #include <functional>
using namespace std; struct Foo { void print_sum(int n1, int n2) { std::cout << n1 + n2 << '\n'; } int data = 10; };
int main(){ Foo foo; auto f5 = std::bind(&Foo::data, std::placeholders::_1); std::cout << f5(foo) << '\n'; }
|
2.3. 使用智能指针调用被引用的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <set> #include <iostream> #include <functional> #include <memory>
using namespace std; struct Foo { void print_sum(int n1, int n2) { std::cout << n1 + n2 << '\n'; } int data = 10; };
int main(){ Foo foo; auto f6 = std::bind(&Foo::data, std::placeholders::_1); std::cout << f6(std::make_shared<Foo>(foo)) << '\n'; }
|
Author:
mxwu
Permalink:
https://mingxuanwu.com/2024/07/15/202407151704/
License:
Copyright (c) 2023 CC-BY-NC-4.0 LICENSE