Because std::function
is copyable, the standard requires that callables used to construct it also be copyable:
n337 (20.8.11.2.1)
template<class F> function(F f);
Requires:
F
shall be CopyConstructible.f
shall be Callable (20.8.11.2) for argument typesArgTypes
and return typeR
. The copy constructor and destructor of A shall not throw exceptions.`
This implies that it is not possible to form an std::function
from a non-copyable bind object or a lambda that captured a move-only type such as std::unique_ptr
.
It seems possible to implement such a move-only wrapper for move-only callables. Is there a standard library move-only equivalent for std::function
or, is there a common workaround for this problem?
As others have pointed out, there is no move-only version of
std::function
in the library. Following is a work-around that the reuses (abuses?)std::function
and allows it to accept move-only types. It is largely inspired by dyp's implementation in the comments, so a lot of the credit goes to him:Working version to coliru.
No, there is no move-only version of
std::function
in the C++std
library. (As of C++14)Fastest possible delegates is an implementation of a
std::function
like class that happens to be faster than moststd::function
implementations in manystd
libraries, and it should be easy to fork into amove
andcopy
version.Wrapping your
move
only function object into ashared_ptr<F>
in a class with a forwardingoperator()
is another approach.Here is a
task
sketch:but it has not been tested or compiled, I just wrote it.
A more industrial strength version would include a small buffer optimization (SBO) to store small callables (assuming they are movable; if not movable, store on heap to allow moving), and a get-pointer-if-you-guess-the-type-right (like
std::function
).