🐭 std::bind
在 C++ 中 std::bind 就是一个通用的函数适配器,它接受一个可调用对象,返回一个新的可调用对象。一般就是结合 std::placeholders 用来做函数适配,修改函数的接口。std::bind 能很好的与 C++ 内置的一些函数对象以及一些工具类一起工作。比如 std::less, std::logical_and, std::not_fn 等等。
代码示例 :
#include <array>#include <iostream>#include <numeric>void identities(int a, int b, int c) {std::cout << "a = " << a << ' ';std::cout << "b = " << b << ' ';std::cout << "c = " << c << '\n';}int main() {using std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::cout;// id0 is same as identitiesauto id0 = std::bind(identities, _1, _2, _3);// id1 need pass int 2 intsauto id1 = std::bind(identities, 1, _1, _2);// id2 need pass in 1 intauto id2 = std::bind(identities, 1, 2, _1);id0(1, 2, 3); // a = 1 b = 2 c = 3id1(2, 3); // a = 1 b = 2 c = 3id2(3); // a = 1 b = 2 c = 3// id3 repeat the passed in valuesauto id3 = std::bind(identities, _1, _1, _1);// id4 changes the passed in values orderauto id4 = std::bind(identities, _3, _1, _2);// id5 ignore some passed in valuesauto id5 = std::bind(identities, 1, 2, _2);id3(4); // a = 4 b = 4 c = 4id4(5, 6, 7); // a = 7 b = 5 c = 6id5(8, 9, 0); // a = 1 b = 2 c = 9// bind by reference and function compositionstd::array<int, 10> A;std::iota(A.begin(), A.end(), 0);int L = 0, U = 0;auto isLessThanU = std::bind(std::less<int>(), _1, std::cref(U));auto isGreaterThanL = std::bind(std::greater<int>(), _1, std::cref(L));auto p = std::bind(std::logical_and<bool>(), isLessThanU, isGreaterThanL);L = 4;U = 9;std::copy_if(A.cbegin(), A.cend(), std::ostream_iterator<int>(cout, " "), p);// 5 6 7 8cout << '\n';return 0;}
:::tips
std::bind 在一些特定的场景下还是很有用的,特别对输入参数的调整与控制,以及函数组合
适配器是一种设计模式,在 STL 里面使用很广泛,比如:
- 容器适配器
- 迭代器适配器
- 算法适配器
- 函数适配器
:::
🐂 Lambda 与 std::bind
在 C++ 中 std::bind 能做的事情,lambda 现在几乎都能做了,而且 lambda 可读性更好,更直观,更高效,基本上可以替换 std::bind。但是 std::bind 也有它的一些用处,上面的代码示例就是 std::bind 优于 lambda 的地方。它们功能重合的部分建议都使用 lambda 来实现。
Lambda:可能会被编译器内联,对优化友好
std::bind:本质上来说是运行时的行为,编译器有时候没法检查编译时错误,更没法对代码进行优化
代码示例 : ```cppinclude
include
include
int main() {
using std::placeholders::_1, std::cout;
// bind by reference and function composition
std::array
// use Lambda
auto p1 = L = std::cref(L), U = std::cref(U) { return i > L && i < U; };
std::copy_if(A.cbegin(), A.cend(), std::ostream_iterator
return 0; } ``` :::tips 使用 Lambda 来实现同样的功能,要比 std::bind 的可读性好很多,编写也更容易直观 :::
🐯 总结
- std::bind 在特定场景下还是有其用武之地
- Lambda 相对于 std::bind,优势明显,可读性好,效率高,表达能力强
