#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
发布于 2012-09-01 05:14:24
不,不,不:你得到的是一个零参数的函数,因为所有的东西都已经绑定了!您需要以下两项之一:
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);}。
发布于 2012-09-01 20:18:48
有两个地方需要查看参数:在调用bind()时,参数成为bind对象的一部分;在调用bind对象本身时,将参数传递给最初调用bind()时建立的占位符。在这里的示例中,对bind()的调用中没有占位符,因此在对bind对象的调用中不需要任何参数。如果调用它时使用的参数比它需要的多,那么多余的参数将被忽略。
此处的代码通过将bind对象包装在std::function对象中来向bind对象添加层。为std::function对象(这里是std::function<void(int)>)定义的签名决定了如何调用该对象:它接受int类型的参数,并将该值传递给绑定对象,后者将忽略该值。
https://stackoverflow.com/questions/12222495
复制相似问题