我应该如何将一个函数作为仿函数传递到结构中?我认为这应该可以正常工作,但事实并非如此:
#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
是一个成员函数,它需要 三个 个参数:i
, j
,以及不可见的隐式 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));
关于c++ - 将结构(或类)的内部函数作为仿函数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543062/