std::bind
当我们更想要在类内定义一个普通函数,并作为排序的规则时应该怎么办?
我们尝试写出如下代码,并成功获得一大堆编译错误。
#include <algorithm> #include <climits> #include <vector> class Cmp { public: bool cmp(const int& a, const int& b) { return a < b; } }; int main(void) { std::vector<int> arr = {INT_MAX, INT_MIN, -1, 0, 1}; // 使用class Cmp 中的 cmp函数 std::sort(arr.begin(), arr.end(), &Cmp::cmp); }法一
当新手去百度答案时,有一种解决方案是在该函数前写出 static。
class Cmp { public: static bool cmp(const int& a, const int& b) { return a < b; } };法二
而另一种方式是使用名为 的函数来处理。具体方案如下。
#include <algorithm> #include <climits> #include <functional> #include <vector> class Cmp { public: bool cmp(const int& a, const int& b) { return a < b; } }; int main(void) { std::vector<int> arr = {INT_MAX, INT_MIN, -1, 0, 1}; // _1, _2占位符的命名空间 using namespace std::placeholders; Cmp obj; auto cmp = std::bind(&Cmp::cmp, &obj, _1, _2); std::sort(arr.begin(), arr.end(), cmp); }原理
我们来分析一下 auto cmp = std::bind(&Cmp::cmp, &obj, _1, _2); ,这个语句。
第一个参数是我们需要调用的函数,第二个是匹配对象的地址,后两个是以下划线 _ 开头的数字。
而为什么方法一的添加 static 也可以呢,因为静态函数不属于类的成员函数,没有隐式的 this 指针。