c++std-functionstdbind

C++ std::bind to std::function with multiple arguments


This question is going to be very much a duplicate, but I've read many of the examples on stack overflow and the common solution is not compiling for me, and I'm trying to figure out why.

So I have a function I want to store in another class, the minimal example of what I'm doing outlined below. It does not compile as this is the issue.

It was working when ParentClass::someFunction only had a single argument, but going to 2, and changing the placeholder to 2 did not work out.

Can someone point out what mistake I am making here?

#include <functional>
#include <string>

class StorageClass{
public:
    //In the actual code it get's passed to another another level 
    //hence why I'm passing by reference rather than value
    void AddFunction(const std::function<void(std::string& a, int b)>& function);

private:
    std::function<void(std::string& a, int b)> callBack;
};


void StorageClass::AddFunction(const std::function<void(std::string& a, int b)>& function){
    callBack = function;
}

class ParentClass {
public:
    ParentClass();
    void someFunction(std::string a, int b);

private:
    StorageClass storageClass;
};

ParentClass::ParentClass() {
    storageClass.AddFunction(std::bind(&ParentClass::someFunction, this, std::placeholders::_2));
}

void ParentClass::someFunction(std::string a, int b) {

}

int main()
{

    ParentClass parentClass;
}

Solution

  • Your function has two parameters, so you need two placeholders in your bind expression.

    std::bind(&ParentClass::someFunction, this, std::placeholders::_2)
    

    needs to be

    std::bind(&ParentClass::someFunction, this, std::placeholders::_1, std::placeholders::_2)
    

    Alternatively you can simplify this with a lambda like

    [this](auto a, auto b){ this->someFunction(a, b); }