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

Replacing std::bind with lambda with a member function to fill vector of function pointer

I have implemented function pointer list that i want to past the function and the object i want to convert the bind to a lambda function but i failed, any help?

#include <iostream>
#include <functional>
#include <vector>

using namespace std;

class Red {
public:
    template <typename F, typename M>
    void addToVector(F f, M m)
    {
        list.push_back(std::bind(f, m));
        cout<<"Function added.";
    }
    
    std::vector<std::function<void()>> list;
};

class Blue {
public:
    Blue()
    {
        r.addToVector(&Blue::someFunc, this);
    }

    void someFunc(){
        cout<<"Some print.";
    }
    
    Red r;
};


int main()
{
    Blue b;
    return 0;
}

I have tried this list.push_back([=](){ return m->f(); });

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

>Solution :

I have tried this list.push_back([=](){ return m->f(); });

The correct syntax to call the member function using a pointer to object would be:

//----------------------------vvvvvv------->correct way to call member function using a pointer to object
list.push_back([=](){ return (m->*f)(); });

Working demo

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