解释如何std::bind
使用的一个简单示例如下:
假设我们有3个参数的函数:f3(x,y,z).我们想要一个2个参数的函数,定义为:f2(x,y) = f3(x,5,y)
.在C++中,我们可以轻松地执行以下操作std::bind
:
auto f2 = std::bind(f3, _1, 5, _2);
Run Code Online (Sandbox Code Playgroud)
这个例子对我很清楚:std::bind
将一个函数作为它的第一个参数,然后它接受另外两个参数,其中n是作为第一个参数的函数的参数个数std::bind
.
但是,我发现另一个使用bind:
void foo( int &x )
{
++x;
}
int main()
{
int i = 0;
// Binds a copy of i
std::bind( foo, i ) (); // <------ This is the line that I do not understand.
std::cout << i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
很明显,foo
有一个论点,std::bind
并设置为i
.但是为什么我们之后又使用另一对括号(foo, i)
?为什么我们不使用输出std::bind
?我的意思是,我们为什么不拥有auto f = std::bind(foo, i)
?
这条线
std::bind( foo, i ) ();
Run Code Online (Sandbox Code Playgroud)
相当于:
auto bar = std::bind( foo, i );
bar();
Run Code Online (Sandbox Code Playgroud)
它创建一个绑定仿函数,然后立即调用它(使用第二对括号).
编辑:在准确性的名称(由@Roman指出,@ daramarak)这两个实际上并不等同于直接调用函数:i通过值传递给std :: bind.相当于foo
直接使用i 调用的代码将是:
auto bar = std::bind( foo, std::ref(i) );
bar();
Run Code Online (Sandbox Code Playgroud)