c++ - 将结构(或类)的内部函数作为仿函数传递

标签 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);
    }
};

得到 <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/

相关文章:

c++ - 如何在带有 STL vector 的 C++ 中使用类似 matlab 的运算符

c++ - 在 gdb 中显示取消引用的 STL 迭代器

haskell - 在打印上应用仿函数

c++ - 从函数返回数组

c++ - 这些 vector 定义是 "constant initialization"吗?

c++ - STL 或 boost 线程安全结构中是否存在用于线程间通信的行为 - 具有队列之类的行为?

c++ - std::search 提取当前迭代器并使用 std::advance 向前移动迭代器

c++ - Windows 上的柯南声明设置未设置,已设置

haskell - 为什么 (a, a) 不是仿函数?

c++ - 将函数模板转换为模板仿函数