我正在尝试创建std::function一个移动捕获lambda表达式.请注意,我可以创建一个移动捕获lambda表达式而不会出现问题; 只有当我尝试将其包装成一个std::function我得到错误时.
例如:
auto pi = std::make_unique<int>(0);
// no problems here!
auto foo = [q = std::move(pi)] {
*q = 5;
std::cout << *q << std::endl;
};
// All of the attempts below yield:
// "Call to implicitly-deleted copy constructor of '<lambda...."
std::function<void()> bar = foo;
std::function<void()> bar{foo};
std::function<void()> bar{std::move(foo)};
std::function<void()> bar = std::move(foo);
std::function<void()> bar{std::forward<std::function<void()>>(foo)};
std::function<void()> bar = std::forward<std::function<void()>>(foo);
Run Code Online (Sandbox Code Playgroud)
我会解释为什么我要写这样的东西.我写了一个UI库,类似于jQuery的或JavaFX的,允许用户通过传递给处理鼠标/键盘事件std::functions到方法有相似的名字on_mouse_down(),on_mouse_drag(),push_undo_action(),等.
显然,std::function我想要传入的理想情况下应该使用移动捕获lambda表达式,否则我需要求助于我在C++ 11作为标准时使用的丑陋的"release/acquire-in-lambda"习语:
std::function<void()> baz = …Run Code Online (Sandbox Code Playgroud) 我一直听到这句话,但我无法真正找到const_cast是邪恶的原因.
在以下示例中:
template <typename T>
void OscillatorToFieldTransformer<T>::setOscillator(const SysOscillatorBase<T> &src)
{
oscillatorSrc = const_cast<SysOscillatorBase<T>*>(&src);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用引用,并使用const,我保护我的引用不被更改.另一方面,如果我不使用const_cast,代码将无法编译.为什么const_cast在这里不好?
这同样适用于以下示例:
template <typename T>
void SysSystemBase<T>::addOscillator(const SysOscillatorBase<T> &src)
{
bool alreadyThere = 0;
for(unsigned long i = 0; i < oscillators.size(); i++)
{
if(&src == oscillators[i])
{
alreadyThere = 1;
break;
}
}
if(!alreadyThere)
{
oscillators.push_back(const_cast<SysOscillatorBase<T>*>(&src));
}
}
Run Code Online (Sandbox Code Playgroud)
请给我一些例子,我可以看到使用const_cast是一个坏主意/不专业.
谢谢你的任何努力:)
MCVE:http : //coliru.stacked-crooked.com/a/ef442eca9b74c8f1
我想按照在 lambda 中移动捕获中的教程来移动lambda 函数中的参数。
#include <string>
#include <iostream>
#include <functional>
class B{};
void f(B&& b){}
int main(){
B b;
auto func_lambda=[b{std::move(b)}](){
//f(std::move(b)); // also fails
f(b); // also fails
};
//: std::function<void()> func_cache=func_lambda();
// will be stored and called after 'b' is out of scope
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:-
main.cpp: 在 lambda 函数中: main.cpp:10:11: 错误: 无法将类型 'B&&' 的右值引用绑定到类型 'const B' 的左值 main.cpp:5:12: 注意:初始化参数 1 of ' void f(B&&)'
我也尝试过[b=std::move(b)]但失败了(链接=通过移动捕获的 lambda 函数传递给函数 …