gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:08:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com