我目前正在开发一个程序,需要使用std :: bind将参数绑定到成员函数,但是当我尝试这样做时,我收到编译器错误。以下是最低限度的示例:
Map.h:
#pragma once
class Map {
void buildDistances();
void buildDistances(unsigned islandId);
};
Map.cpp:
#include "Map.h"
#include <functional>
void Map::buildDistances() {
for(unsigned islandId=0;islandId<24;++islandId){
auto f = std::bind(&Map::buildDistances, this, islandId);
f();
}
}
void Map::buildDistances(unsigned islandId) {}
使用与这两个文件位于同一目录中的命令g++ Map.cpp -c -o map.o
进行编译会产生以下错误:
Map.cpp: In member function ‘void Map::buildDistances()’:
Map.cpp:7:64: error: no matching function for call to ‘bind(<unresolved overloaded function type>, Map*, unsigned int&)’
auto f = std::bind(&Map::buildDistances, this, islandId);
^
In file included from Map.cpp:3:
/usr/include/c++/8.1.1/functional:808:5: note: candidate: ‘template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__is_socketlike<_Func>::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)’
bind(_Func&& __f, _BoundArgs&&... __args)
^~~~
/usr/include/c++/8.1.1/functional:808:5: note: template argument deduction/substitution failed:
Map.cpp:7:64: note: couldn't deduce template parameter ‘_Func’
auto f = std::bind(&Map::buildDistances, this, islandId);
^
In file included from Map.cpp:3:
/usr/include/c++/8.1.1/functional:832:5: note: candidate: ‘template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)’
bind(_Func&& __f, _BoundArgs&&... __args)
^~~~
/usr/include/c++/8.1.1/functional:832:5: note: template argument deduction/substitution failed:
Map.cpp:7:64: note: couldn't deduce template parameter ‘_Result’
auto f = std::bind(&Map::buildDistances, this, islandId);
为什么会发生这种情况,我该如何解决?我试图通过将部分错误放在搜索引擎中来找到结果,但没有任何有用的结果。我也尝试用clang进行编译,这会产生同样的错误。
答案 0 :(得分:4)
之所以发生这种情况,是因为你的功能超载了,std::bind
不知道功能签名,因此无法区分它们。
简单的解决方案?重命名功能。
不太容易的解决方案:将指向函数的指针转换为正确的类型。