一个解释如何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);
这个例子对我来说很清楚:std::bind
将一个函数作为它的第一个参数,然后它接受 n 个其他参数,其中 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;
}
很明显,foo
有一个参数,并且std::bind
设置为i
。但是为什么我们要在 之后使用另一对括号(foo, i)
呢?为什么我们不使用输出std::bind
?我的意思是,为什么我们没有auto f = std::bind(foo, i)
?