【发布时间】:2015-11-08 08:12:56
【问题描述】:
考虑以下示例:
#include <iostream>
#include <functional>
using namespace std;
void f(int x,int y) {}
// void f(int x) {} // if this line is uncommented, code does not compile.
int main() {
auto functor = std::bind(&f,1,placeholders::_1);
cout << "works!" << endl;
return 0;
}
它可以正常编译和运行 (https://ideone.com/fork/2SywE2),但取消注释注释行会导致编译器错误:
prog.cpp:在函数“int main()”中: prog.cpp:10:48: 错误: 没有匹配函数调用'bind(, int, const std::_Placeholder&)' 自动函子 = std::bind(&f,1,placeholders::_1); ^ 在 prog.cpp:2:0 包含的文件中: /usr/include/c++/5/functional:1462:5: 注意:候选:模板类型名 std::_Bind_helper::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ... ) 绑定(_Func&& __f, _BoundArgs&&... __args) ^ /usr/include/c++/5/functional:1462:5: 注意:模板参数推导/替换失败: prog.cpp:10:48:注意:无法推断模板参数“_Func” 自动函子 = std::bind(&f,1,placeholders::_1); ^ 在 prog.cpp:2:0 包含的文件中: /usr/include/c++/5/functional:1490:5:注意:候选:模板类型名 std::_Bindres_helper<_result _func _boundargs>::type std::bind(_Func&&, _BoundArgs&& ...) 绑定(_Func&& __f, _BoundArgs&&... __args) ^ /usr/include/c++/5/functional:1490:5:注意:模板参数推导/替换失败: prog.cpp:10:48:注意:无法推断模板参数“_Result” 自动函子 = std::bind(&f,1,placeholders::_1);
如果存在多个重载,为什么 std::bind 无法解析模板参数,因为重载具有不同数量的输入参数,并且调用 bind 意味着输入参数的数量为 2。
【问题讨论】:
标签: templates c++11 lambda std-function