C++ 作为函子传递结构(或类)的内部函数
我应该如何在结构中作为函子传递函数?我认为这应该很好,但事实并非如此:C++ 作为函子传递结构(或类)的内部函数,c++,stl,functor,function-object,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); } }; #包括 使用名称空间std; 结
#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);
}
};
#包括
使用名称空间std;
结构{
INTA[10];
布尔cmp(整数i,整数j){
//归还某物
}
void init(){
排序(a,a+10,cmp);
}
};
它获取
您不能直接执行此操作,因为cmp
是一个成员函数,它需要三个参数:i
,j
,以及不可见的隐式this
指针
要将cmp
传递到std::sort
,请将其设置为静态函数,该函数不属于s
的任何特定实例,因此没有此
指针:
static bool cmp(int i, int j) {
// return something
}
如果需要访问
此
,可以将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 answer完全可以工作,但您甚至可以使用
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 );} );
为什么我们要用静态的呢?这是做什么的?@typedeftypename静态成员函数基本上是命名空间中的自由函数,恰好是类。@typedeftypename:
static
使它从需求中消失,这个隐式this
。有了它,函数只需要两个参数,i
和j
,它们都在那里。哇,太棒了!我想这应该是c++0x的魔力。太糟糕了,我不能在我的情况下使用它。你可以用boost::bind
代替std::bind
,实际上我目前正为此使用它!