[英]Passing inner function of a struct (or class) as a functor
我應該如何將結構中的函數作為仿函數傳遞? 我認為這應該工作正常,但它沒有:
#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));
雖然@Thomas的答案完全正常,但您甚至可以使用std::bind
或lambdas更簡單地執行以下操作:
// 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 );} );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.