【发布时间】:2017-05-16 18:31:03
【问题描述】:
我编写了一个代码来传递函数指针列表(按其名称)作为参数。但我有错误。你能解释一下为什么我在做地图时出错
#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&, int> ::类型)'
【问题讨论】:
-
void (*)(int,int)没有。Bar::bar偷偷地还收了一个Bar会员。你为什么不直接使用std::function? -
您正在尝试将指向成员函数的指针分配给指向函数的指针。这不被允许。就是这样。
-
在将
&Bar::bar放入地图并将其拉回调用之前,请尝试直接调用。&Bar::bar(2);有用吗?你认为它会起作用吗?
标签: c++ c++11 pointers dictionary vector