Using generic std::function objects with member functions in one class

前端 未结 6 2132
遥遥无期
遥遥无期 2020-11-22 09:41

For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail rig

6条回答
  •  心在旅途
    2020-11-22 10:13

    A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.

    Because your std::function signature specifies that your function doesn't take any arguments (), you must bind the first (and the only) argument.

    std::function f = std::bind(&Foo::doSomething, this);
    

    If you want to bind a function with parameters, you need to specify placeholders:

    using namespace std::placeholders;
    std::function f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
    

    Or, if your compiler supports C++11 lambdas:

    std::function f = [=](int a, int b) {
        this->doSomethingArgs(a, b);
    }
    

    (I don't have a C++11 capable compiler at hand right now, so I can't check this one.)

提交回复
热议问题