如何在这里正确使用bind
How to use bind correctly here?
我不知道绑定成员函数的正确语法。如果我有一个函数,它接受一个只有一个参数的函数,我如何传递一个对象给它?
在下面的例子中,传递函数的正确语法是什么?
#include <iostream>
#include <functional>
void caller(std::function<void(int)> f)
{
f(42);
}
class foo
{
public:
void f(int x)
{
std::cout<<x<<std::endl;
}
};
int main()
{
foo obj;
caller(std::bind(&foo::f,obj));
//^Wrong
}
错误的是:
a.cpp: In function ‘int main()’:
a.cpp:18:34: error: could not convert ‘std::bind(_Func&&, _BoundArgs&& ...) [with _Func = void (foo::*)(int); _BoundArgs = {foo&}; typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type = std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>]((* & obj))’ from ‘std::_Bind_helper<false, void (foo::*)(int), foo&>::type {aka std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>}’ to ‘std::function<void(int)>’
caller(std::bind(&foo::f,obj));
占位符为稍后绑定的实际参数创建一个"空格":
int main()
{
foo obj;
caller(std::bind(&foo::f, &obj, std::placeholders::_1));
// ^ placeholder
// ^ address or even foo()
}
这些占位符需要正确地生成一个合适的签名,以便将std::bind
结果绑定到std::function<void(int)>
。
你可能还想使用你的对象的地址,或者std::ref
(这样它就不会被复制);这取决于您想要的语义。
成员函数有一个隐式的第一个参数,即this
点。你需要给它发送作为指针;您还需要int
参数的占位符。所以:
caller(std::bind(&foo::f, &obj, std::placeholders::_1));
// ^ ^^^^^^^^^^^^^^^^^^^^^^^
您需要使用占位符指定创建的函数对象接受参数:
std::bind(&foo::f,obj, std::placeholders::_1)
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- File.cpp.o:OpenPose 标志 CMakeFiles/.. 的多重定义/main.cpp.o:首先在这里定
- 为什么thread_local变量在这里从未初始化?
- 为什么我必须在这里使用dynamic_cast
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 为什么 C++20 中的 [[可能]] 属性在这里引发警告?
- 我在这里正确传递参数了吗?
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- 移动语义在这里如何工作?
- 如何在这里循环运行?
- 为什么枚举变量在这里是右值?
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 试图美化这个Arduino代码[初学者在这里]
- 复制交换习惯用法-我们可以在这里使用动态强制转换操作吗
- 在这里使用删除运算符是否正确,我很困惑
- 如何使用模板生成整数序列在这里工作
- 如何在这里正确使用bind