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

Passing inner function of a struct (or class) as a functor

本文关键字:内部函数 结构 或类      更新时间:2023-10-16

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

#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);
    }
};

<unresolved overloaded function type>

你不能直接执行此操作,因为cmp是一个成员函数,它需要三个参数:ij和不可见的隐式this指针。

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

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

如果您需要访问 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
    }
};

并像这样称呼它:

sort(a, a + 10, cmp(*this));

虽然@Thomas答案完全有效,但您甚至可以使用 std::bind 或 lambda 更简单,如下所示:

// Using std::bind
std::sort( a, a + 10, std::bind(&s::cmp, this, _1, _2) );
// Using lambdas
std::sort( a, a + 1, [this](int i, int j) {return this->cmp( i, j );} );