C++ 使用std::ref参数调用std::bind(ed)函数 #包括 #包括 结构测试 { void fnc(int&a){++a;} }; int main() { typedef std::function Func; int i=0; 试验t; Func f=std::bind(&Test::fnc,&t,std::ref(i)); //f();//错误C2064:该术语的计算结果不是采用0个参数的函数 f(37);//在这里,我被迫通过int std::cout

C++ 使用std::ref参数调用std::bind(ed)函数 #包括 #包括 结构测试 { void fnc(int&a){++a;} }; int main() { typedef std::function Func; int i=0; 试验t; Func f=std::bind(&Test::fnc,&t,std::ref(i)); //f();//错误C2064:该术语的计算结果不是采用0个参数的函数 f(37);//在这里,我被迫通过int std::cout,c++,c++11,C++,C++11,No-No:您拥有的是一个具有零参数的函数,因为所有内容都已绑定!您需要以下两个选项之一: #include <functional> #include <iostream> struct Test { void fnc(int & a) { ++a; } }; int main () { typedef std::function<void(int)> Func; int i = 0; Test t; F

No-No:您拥有的是一个具有零参数的函数,因为所有内容都已绑定!您需要以下两个选项之一:

#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;
}

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

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


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

一个问题,是否可以按ref传递,但在调用过程中提供变量,而不是在绑定过程中?或者如果我不想复制整个对象(这里的int是错误的示例)我使用占位符,但使用指针?@relaxx:g
g
不完全符合这些要求吗?(请注意我刚才所做的更正;它现在引用了。)哦,是的。我只是在脑子里想了一下:
注意,要绑定的参数是复制或移动的,除非用std::ref或std::cref包装,否则永远不会通过引用传递。
我理解错了,还是错了?哦!要绑定的参数…我现在理解了:)我应该睡一觉:)非常感谢你的帮助
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);
f();  // OK, bound to `i` always.

g(i); // Same effect