Yur*_*kyi 2 c++ lambda move c++11
在我的代码中,我使用了来自Scott Meyers Effective Modern C++的Item 32建议,在那里他解释了如何在C++ 11中进入捕获.示例代码运行良好.
class Some
{
public:
void foo()
{
std::string s = "String";
std::function<void()> lambda = std::bind([this](std::string& s) {
bar(std::move(s));
}, std::move(s));
call(std::move(lambda));
}
void bar(std::string)
{
// Some code
}
void call(std::function<void()> func)
{
func();
}
};
int main()
{
Some().foo();
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用参数中更难以捕获的方式移动,但它不起作用,存在一些编译错误.请帮我修理一下.代码有错误如下.我玩过它,但找不到解决方案.有可能吗?
class Some
{
public:
void foo()
{
std::string stringToMove = "String";
std::function<void(std::string, int, int)> lambda =
std::bind([this](std::string s, int i1, int i2, std::string& stringToMove) {
bar(std::move(stringToMove), i1, i2);
}, std::move(stringToMove));
call(std::move(lambda));
}
void bar(std::string, int, int)
{
// Some code
}
void call(std::function<void(std::string, int, int)> func)
{
func(std::string(), 5, 5);
}
};
int main()
{
Some().foo();
}
Run Code Online (Sandbox Code Playgroud)
错误:
严重级代码描述项目文件行抑制状态错误C2672'std :: invoke':找不到匹配的重载函数草稿c:\ program files(x86)\ microsoft visual studio 14.0\vc\include\type_traits 1468
严重级代码描述项目文件行抑制状态错误C2893无法专门化函数模板'unknown-type std :: invoke(_Callable &&,_ Types && ...)'草稿c:\ program files(x86)\ microsoft visual studio 14.0\vc\include\type_traits 1468
std::bind要求您指定所有参数.那些应该传递给结果函数对象的东西需要是占位符.
std::function<void(std::string, int, int)> lambda =
std::bind([this](std::string s, int i1, int i2, std::string& stringToMove) {
bar(std::move(stringToMove), i1, i2);
}, _1, _2, _3, std::move(stringToMove));
Run Code Online (Sandbox Code Playgroud)