函数适配器
用下面一个简单的例子来演示一下函数适配器的作用。
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
bool is_negative(const int& a, const int& b) {
return a < 0;
}
int main() {
std::vector<int> vec = {-1, -2, -3, 4, 5};
auto Mf = std::bind(is_negative, std::placeholders::_1, 0);
auto result = count_if(vec.begin(), vec.end(), Mf);
std::cout << result << "\n";
return 0;
}
为啥要使用函数适配器
其实要实现上面的功能,我们完全可以写一个类似 bool is_negative(const int& a) 的函数,或者直接使用 lambda 表达式。但是,如果我们需要使用一个更复杂的函数,而且可能我们原有的 code base 或者 操作系统已经自带了一个可用,但是参数不同的函数。我们这个时候就可以使用函数适配器去简化我们的代码。