为什么std :: bind无法解析具有多个参数的函数重载?

Ily*_*kiy 5 lambda templates c++11 std-function

考虑以下示例:

#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;
}
Run Code Online (Sandbox Code Playgroud)

它可以按原样(https://ideone.com/fork/2SywE2)进行编译和运行,但是取消注释注释行会导致编译器错误:

prog.cpp:在函数'int main()'中:prog.cpp:10:48:错误:没有匹配的函数调用'bind(,int,const std :: _ Placeholder <1>&)'auto functor = 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 && ...)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);

如果存在多个重载,为什么std :: bind无法解析模板参数,因为重载具有不同的输入参数数字,并且对bind的调用意味着输入参数的数量为2。

Ste*_*oft 5

当 C++ 编译器看到对 的调用时std::bind(&f,1,placeholders::_1),它不知道参数之间的任何关系。关系仅在实例化模板时可见。为了实例化它,编译器需要模板参数。但是&f是一个重载函数,所以它没有定义的类型。因此,C++ 编译器无法实例化模板,因此即使在任何关系可见之前编译也会失败。

您可以通过明确指定类型来解决此问题:

std::bind(static_cast<void(*)(int,int)>(&f),1,placeholders::_1);
Run Code Online (Sandbox Code Playgroud)