将结构(或类)的内部函数作为函子传递

SeM*_*eKh 2 c++ stl functor function-object

我应该如何将结构中的函数作为仿函数传递?我认为这应该工作正常,但它没有:

#include <algorithm>
using namespace std;

struct s {
    int a[10];

    bool cmp(int i, int j) {
        // return something
    }

    void init() {
        sort(a, a + 10, cmp);
    }
};
Run Code Online (Sandbox Code Playgroud)

得到了 <unresolved overloaded function type>

Tho*_*mas 6

你不能直接这样做,因为cmp是一个成员函数,它需要3个参数:i,j,和无形的,隐含的this指针.

要传递cmpstd::sort它,使它成为一个静态函数,它不属于任何特定的实例,s因此没有this指针:

static bool cmp(int i, int j) {
    // return something
}
Run Code Online (Sandbox Code Playgroud)

如果需要访问权限this,则可以包含cmp一个简单的函数对象:

struct cmp {
    s &self;
    cmp(s &self) : self(self) { }
    bool operator()(int i, int j) {
        // return something, using self in the place of this
    }
};
Run Code Online (Sandbox Code Playgroud)

并称之为:

sort(a, a + 10, cmp(*this));
Run Code Online (Sandbox Code Playgroud)