Home > Software design >  Replacing std::bind with lambda with a member function to fill vector of function pointer
Replacing std::bind with lambda with a member function to fill vector of function pointer

Time:08-18

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(); });

CodePudding user response:

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

  • Related