请考虑以下示例:
#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 <1>&)'auto functor = std ::绑定(&F,1,占位符:: _ 1); ^在prog.cpp中包含的文件中:2:0:/ usr / include / c / 5 / functional:1462:5:注意:候选:模板类型名称std :: _ Bind_helper :: value,_Func,_BoundArgs ...>: :type std :: bind(_Func &&,_BoundArgs && ...)bind(_Func && __f,_BoundArgs && ... __args)^ / usr / include / c / 5 / functional:1462:5:注意:模板参数扣除/替换失败: prog.cpp:10:48:注意:无法推断出模板参数'_Func'auto functor = std :: bind(&f,1,placeholders :: _ 1); ^在prog.cpp中包含的文件中:2:0:/ usr / include / c / 5 / functional:1490:5:注意:候选人:模板typename std :: _ Bindres_helper <_Result,_Func,_BoundArgs> :: type std: :bind(_Func &&,_BoundArgs && ...)bind(_Func && __f,_BoundArgs && ... __args)^ / usr / include / c / 5 / functional:1490:5:注意:模板参数推断/替换失败:prog.cpp: 10:48:注意:无法推断出模板参数'_Result'auto functor = std :: bind(&f,1,placeholders :: _ 1);
如果存在多个重载,为什么std :: bind无法解析模板参数,因为重载具有不同的输入参数,并且调用bind意味着输入参数的数量为2 .
1 回答
当C编译器看到对
std::bind(&f,1,placeholders::_1)
的调用时,它不知道参数之间的任何关系 . 只有在实例化模板时,关系才可见 . 要实例化它,编译器需要模板参数 . 但&f
是一个重载函数,所以它没有定义类型 . 因此,C编译器无法实例化模板,因此即使在可以看到任何关系之前编译也会失败 .您可以通过明确指定类型来解决此问题: