将结构(或类)的内部函数作为函子传递
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
或 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 );} );
相关文章:
- C++ SSE 内部函数:将结果存储在变量中
- C++代码停止工作错误使用cout内部函数
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- 使用英特尔内部函数 (AVX) 中的混合说明
- 英特尔汇编与内部函数,AVX
- 使用SSE内部函数复制少量数据时出现问题
- 在为函数编写单元测试时,我应该模拟所做的内部函数调用吗?
- 用于平铺矩阵乘法的 AVX 内部函数
- 是否可以使用类的析构函数内部函数来重置值?
- C++ 从内部破坏结构
- 函数:结构的数组
- 我在理解 AVX 随机内部函数如何为 8 位时遇到一些问题
- 无法执行内部函数 strlen
- COUT 内部函数调用的顺序
- 通过Visual Studio将小型结构逐值传递到非内部函数的速度很慢
- C++读取函数内部的结构数组
- 将结构(或类)的内部函数作为函子传递
- 在结构数组上C++ qsort 内部函数
- 访问在 C++ 函数内部的结构中定义的枚举类属性
- 使用类的成员函数访问内部的结构成员时出错