簡體   English   中英

將結構(或類)的內部函數作為函子傳遞

[英]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是一個成員函數,它需要三個參數: 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或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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM