gpt4 book ai didi

c++ - 如何从移动捕获 lambda 表达式创建 std::function?

转载 作者:行者123 更新时间:2023-12-02 04:27:01 26 4
gpt4 key购买 nike

我正在尝试创建一个 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);

我会解释为什么我想写这样的东西。我编写了一个 UI 库,它类似于 jQuery 或 JavaFX,允许用户通过传递 std::function 来处理鼠标/键盘事件。 s 到名称类似于 on_mouse_down() 的方法, on_mouse_drag() , push_undo_action()

显然,std::function我想传入应该理想地使用移动捕获 lambda 表达式,否则我需要求助于我在 C++11 是标准时使用的丑陋的“release/acquire-in-lambda”习惯用法:

std::function<void()> baz = [q = pi.release()] {
std::unique_ptr<int> p{q};
*p = 5;
std::cout << *q << std::endl;
};

注意调用baz twice 将是上述代码中的错误。然而,在我的代码中,这个闭包保证只被调用一次。

顺便说一句,在我的真实代码中,我没有传递 std::unique_ptr<int> , 但更有趣的东西。

最后,我使用了 Xcode6-Beta4,它使用了以下版本的 clang:

Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

最佳答案

template<class F> function(F f);

template <class F, class A> function(allocator_arg_t, const A& a, F f);

Requires: F shall be CopyConstructible. f shall be Callable for argument types ArgTypes and return type R. The copy constructor and destructor of A shall not throw exceptions.

§20.9.11.2.1 [func.wrap.func.con]

请注意 operator =是根据此构造函数和 swap 定义的,所以同样的限制适用:

template<class F> function& operator=(F&& f);

Effects: function(std::forward<F>(f)).swap(*this);

§20.9.11.2.1 [func.wrap.func.con]

所以回答你的问题:是的,可以构造一个 std::function来自移动捕获 lambda(因为这仅指定了 lambda 捕获的方式),但不可能构造 std::function来自仅移动类型(例如移动捕获 lambda,它移动捕获不可复制构造的内容)。

关于c++ - 如何从移动捕获 lambda 表达式创建 std::function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53495191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com