调用函数,该函数是 std::bind(ed) 与 std::ref 参数
calling function which was std::bind(ed) with std::ref argument
#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 对象,绑定对象忽略它。
相关文章:
- 使用std::函数映射对象方法
- 可组合的lambda/std::函数与std::可选
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- std::函数常量正确性未遵循
- 具有变量Number of Arguments的std::函数的矢量
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 如何将类 1 的 std::函数绑定到类 2 的函数?
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- 如何将 STL 队列推送函数绑定到 std::函数?
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- 获取 std::函数以推断按引用传递/按值传递
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 从其存储的回调中删除 std::函数是否安全
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 创建一个带有 lambda 的 std::函数,而不知道函数的参数
- std::函数的解释
- 在调用过程中删除 std::函数