c++ - 将非静态成员函数作为 std::function 传递

标签 c++ std-function

<分区>

我也有类似的情况:

class A {
    void callingFunction() {
      calledFunction(passedFunction);
    }

    void calledFunction(std::function<void(int)> foo) {
    }

    void passedFunction(int arguments) {
    }
};

编译错误是

error: invalid use of non-static member function

如何在不使 passedFunction 静态化的情况下实现这一点?

这样做:

calledFunction(std::bind(&A::passedFunction, this);

创建此错误:

error:static assertion failed: Wrong number of arguments foor pointer-to-member

这是否意味着我必须在传递 passedFunction 时提供 callingFunction 中的所有参数?这是不可能的,因为 passedFunction 的参数在 calledFunction

中指定

最佳答案

你可以写一个lambda捕获 this,可以在其上调用 passedFunction

calledFunction([this](int v) { this->passedFunction(v); });

关于c++ - 将非静态成员函数作为 std::function 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50449052/

相关文章:

c++ - 将颜色从RGB转换为NV12

c++11 - std::function 是如何为 lambda 构造的

c++ - 基于 sizeof c++ 的条件语句的问题

c++ - Gstreamer audiofirfilter

function - 如何将多态性与 std::function 结合使用?

c++ - 什么时候应该存储函数的引用或指针?

c++17:lambda 到 std::function 转换失败

c++ - std::function typedef 中的参数名称

c++ - QT:没有百分比编码的 QUrl

数组中对象的 C++ 多态性