c++ - 将成员函数指针的 vector 传递给函数

标签 c++ c++11 pointers dictionary vector

我编写了一段代码来传递一个函数指针列表(按其名称)作为参数。但是我有错误。你能解释一下为什么我在做 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;
}

错误:

34:18:错误:无法将“void (Bar::)(int, int)”转换为“std::map, void (*)(int, int)>::mapped_type {aka void ()(int, int)}' 在赋值中

35:18:错误:无法将“void (Foo::)(int, int)”转换为“std::map, void (*)(int, int)>::mapped_type {aka void ()(int, int)}' 在赋值中

41:70: 错误:没有匹配函数来调用 'std::vector >::push_back(std::_Bind_helper&)(int, int), Bar, const std::_Placeholder<1>&, int>::类型)'

最佳答案

成员函数需要知道它们是哪个对象的成员,以便它们可以对正确的 this 进行操作。

因此,您需要确保存储在 map 中的函数知道它将来是哪个对象的成员。

int main() {
  using namespace std::placeholders;
  Foo foo;
  Bar bar;
  std::map<std::string, std::function<void(int, int)>> myMap;
  myMap["bar"] = std::bind(&Bar::bar, &bar, _1, _2);
  myMap["foo"] = std::bind(&Foo::foo, &foo, _1, _2);

稍后它已经知道它是哪个对象的成员,你不需要再告诉它:

  // ..
  listofName.push_back(std::bind(myMap[s1], _1, 1));
  listofName.push_back(std::bind(myMap[s2], _1, 3));

关于c++ - 将成员函数指针的 vector 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430403/

相关文章:

c++ - 如何获取当前用户权限组?

c++ - 我还应该在 C++11 中返回 const 对象吗?

c - 如何将多维指针/数组传递给递归函数

c++ - C26486 - 不要将可能无效的指针传递给函数?

c++ - 为什么在 SFINAE 中调用该函数不会产生歧义?

c++ - 使用 qsort() 时包含 C++ 字符串的类的排序不正确/错误

c++ - 从其他函数调用 WinMain

c++ - OS X 上的 std::locale 段错误,无法在任何其他平台上重现

c++ - 连通分量程序产生不正确的输出

c - 在我的 C 认证考试练习中需要帮助解密神秘代码