c++ - 为什么 std::bind 绑定到成员函数时不会编译?
问题描述
我目前正在开发一个需要使用 std::bind 将参数绑定到成员函数的程序,但是当我尝试这样做时,出现编译器错误。以下是一个最小示例:
地图.h:
#pragma once
class Map {
void buildDistances();
void buildDistances(unsigned islandId);
};
地图.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 进行编译,这会产生相同的错误。
解决方案
发生这种情况是因为您重载了函数,并且std::bind
不知道函数签名,因此无法区分它们。
简单的解决方案?重命名函数。
不太简单的解决方案:将指向函数的指针转换为正确的类型。
推荐阅读
- api - 要么/或身体属性和多个示例
- java - 无法打开 sqlite 数据库,指定的目录或数据库文件不存在
- laravel - Laravel 5.8 / VueJs 2 / Axios GET 请求不发送 cookie(CORS、子域)
- c# - 如何为此数据编写 LINQ
- c# - C#如何将图像文件打开为位图但按比例缩小?
- flutter - FutureBuilder 运行两次
- merge - 在 CR 中,您可以将多行合二为一吗?
- python - Pandas 数据帧到基于组分配的稀疏矩阵(如果在组中,则为 1,如果不在组中,则为 0)
- java - 在 mvn 包阶段在 Dockerfile 中包含本地 Maven m2 存储库?
- reactjs - 打开时控制反应选择菜单滚动位置