Home >Backend Development >C++ >Can I Create an `std::function` from a Move-Capturing Lambda Expression?

Can I Create an `std::function` from a Move-Capturing Lambda Expression?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 13:46:11974browse

Can I Create an `std::function` from a Move-Capturing Lambda Expression?

Creating 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:

  • The lambda expression's capture must be copy-constructible.
  • The lambda expression must be Callable with the specified argument types and return type.
  • The lambda's capture's copy constructor and destructor must not throw exceptions.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn