C++ std::绑定和右值引用 让我们考虑下面的代码: class Widget{ }; int main(){ Widget w; auto lambda = bind([](Widget&& ref){ return; }, std::move(w)); return 0; }
它会引发错误C++ std::绑定和右值引用 让我们考虑下面的代码: class Widget{ }; int main(){ Widget w; auto lambda = bind([](Widget&& ref){ return; }, std::move(w)); return 0; },c++,c++11,rvalue-reference,C++,C++11,Rvalue Reference,它会引发错误 对“(std::_Bind)()的调用不匹配” lambda(); 我的问题是:为什么会出现错误?毕竟,我对右值引用进行了显式转换–我的意思是std::move(w),我通过右值引用获取参数–我的意思是Widget&&ref 怎么了 此外,下面的代码有效,是什么让我更担心: class Widget{ }; int main(){ Widget w; auto lambda = bind([](Widget& ref){ return; }, std::move(w))
对“(std::_Bind)()的调用不匹配”
lambda();
我的问题是:为什么会出现错误?毕竟,我对右值引用进行了显式转换–我的意思是std::move(w)
,我通过右值引用获取参数–我的意思是Widget&&ref
怎么了
此外,下面的代码有效,是什么让我更担心:
class Widget{
};
int main(){
Widget w;
auto lambda = bind([](Widget& ref){ return; }, std::move(w));
return 0;
}
如果你把std::bind的功能写下来,它可能会变得更清晰
// C++14, you'll have to write a lot of boilerplate code for C++11
template <typename FuncT, typename ArgT>
auto
bind(FuncT&& func, ArgT&& arg)
{
return
[
f = std::forward<FuncT>(func),
a = std::forward<ArgT>(arg)
]() mutable { return f(a); }; // NB: a is an lvalue here
}
要让它工作,你需要这样写:
#include <functional>
#include <iostream>
class Widget{};
int main()
{
Widget a;
auto lf = [](Widget&& par){ };
auto f = std::bind
(
lf,
std::bind
(
std::move<Widget&>, a
)
);
f();
return 0;
}
#包括
#包括
类控件{};
int main()
{
小部件a;
自动lf=[](小部件和par){};
自动f=std::bind
(
如果,
绑定
(
移动,移动
)
);
f();
返回0;
}
我的编译器是
gcc版本4.9.2 20141101(Red Hat 4.9.2-1)(gcc)
您是如何发现此示例不起作用的?我用我的编译器成功地编译了它。你使用什么编译器?对不起,我对我的过程的命名感到困惑,GCC没有告诉我有两个函数要调用。