Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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); }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading