lundi 2 janvier 2017

C++: Pass a vector of member function pointer to a function

I've written a code to pass a list of function pointer (by its name) as argument. But I have error. Can you explain why I have error while doing map

#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include <map>

class Foo
{
public:
    void foo(int a, int b)
    {
        std::cout << a <<" "<< b<<'\n';
    }
};

class Bar
{
public:
    void bar(int a, int b)
    {
        std::cout << a<<" "<< b << '\n';
    }
};


int main()
{

    Foo foo;
    Bar bar;
    std::map<std::string,  void (*)(int,int)>myMap;
    myMap["bar"] = &Bar::bar;
    myMap["foo"] = &Foo::foo;

    std::vector<std::function<void (int )>> listofName;
    std::string s1("bar");
    std::string s2("foo");

    listofName.push_back(bind(myMap[s1],&bar,std::placeholders::_1,1));
    listofName.push_back(bind(myMap[s2],&foo,std::placeholders::_1,3));

    for (auto f : listofName) {
        f(2);
    }

 return 0;
}

Error:

34:18: error: cannot convert 'void (Bar::)(int, int)' to 'std::map, void (*)(int, int)>::mapped_type {aka void ()(int, int)}' in assignment

35:18: error: cannot convert 'void (Foo::)(int, int)' to 'std::map, void (*)(int, int)>::mapped_type {aka void ()(int, int)}' in assignment

41:70: error: no matching function for call to 'std::vector >::push_back(std::_Bind_helper&)(int, int), Bar, const std::_Placeholder<1>&, int>::type)'

Aucun commentaire:

Enregistrer un commentaire