Home >Backend Development >C++ >Can I Create an `std::function` from a Move-Capturing Lambda Expression?
It is possible to construct an std::function from a move-capturing lambda expression; however, certain restrictions apply.
Template Constructor
An std::function can be constructed from a move-capturing lambda using the following template constructor:
template<class F> function(F f);
Requirements
For this constructor to work, the following requirements must be met:
Move-Only Types
It is not possible to construct an std::function from a lambda that move-captures a move-only type. This is because std::function's copy constructor and assignment operator are defined in terms of a constructor that requires copy-constructible types.
Example
Consider the following code snippet:
auto pi = std::make_unique<int>(0); // Move-capturing lambda auto foo = [q = std::move(pi)] { *q = 5; std::cout << *q << std::endl; };
Attempting to create an std::function from this lambda using any of the following approaches will result in a compilation error:
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);
This is because pi is a move-only type, and std::function's copy constructor requires copy-constructible types.
Therefore, if you wish to use a move-capturing lambda with std::function, ensure that its capture is copy-constructible.
The above is the detailed content of Can I Create an `std::function` from a Move-Capturing Lambda Expression?. For more information, please follow other related articles on the PHP Chinese website!