调用函数,该函数是 std::bind(ed) 与 std::ref 参数

calling function which was std::bind(ed) with std::ref argument

本文关键字:std 函数 参数 ref ed bind 调用      更新时间:2023-10-16
#include <functional>
#include <iostream>
struct Test
{
    void fnc(int & a) { ++a; }
};
int main ()
{
    typedef std::function<void(int)> Func;
    int i = 0;
    Test t;
    Func f = std::bind(&Test::fnc, &t, std::ref(i));
    //f(); //error C2064: term does not evaluate to a function taking 0 arguments
    f(37); //Here I am forced to pass evidently unused int
    std::cout << i;
}

我用得对吗?

真的有必要传递一些随机的 int 吗?

如果是这样,为什么会这样?那是因为模板的魔力是有限的,我实际上必须将 int 传递给函数,取 int 还是出于某些目的而设计的?(例如,强制用户不要忘记函数的声明已经是什么样子的?

我使用 vs2012

不不不:你有一个接受参数的函数,因为一切都已经绑定了!您需要以下两个之一:

std::function<void()> f = std::bind(&Test::fnc, &t, std::ref(i));
std::function<void(int&)> g = std::bind(&Test::fnc, &t, std::placeholders::_1);

现在t.fnc(i)以下两个效果:

f();  // OK, bound to `i` always.
g(i); // Same effect

请注意,如果可能的话,你应该将绑定函数声明为 auto ,这样更有效。第三个选项是闭包表达式,[&i,&t](){t.fnc(i);} .

在两个地方,您必须查看参数:在对bind()的调用中,参数成为绑定对象的一部分,以及在对绑定对象本身的调用中,参数将传递给在原始调用中建立的占位符 bind() 。在此示例中,对 bind() 的调用中没有占位符,因此在对 bind 对象的调用中不需要任何参数。如果使用比需要的参数多的参数调用它,则会忽略多余的参数。

此处的代码通过将绑定对象包装在std::function对象中来向绑定对象添加一个层。为std::function对象定义的签名(此处为 std::function<void(int)> (确定如何调用该对象:它接受类型 int 的参数并将该值传递给 bind 对象,绑定对象忽略它。