Introducing folly::Function
authorSven Over <over@fb.com>
Tue, 22 Mar 2016 13:10:19 +0000 (06:10 -0700)
committerFacebook Github Bot 9 <facebook-github-bot-9-bot@fb.com>
Tue, 22 Mar 2016 17:35:21 +0000 (10:35 -0700)
commit08a67734a964c129f3675c159b40af8a9b26fc12
tree7c1e1754d33778b1dde5de16de49d2e6b9e1fd35
parent328b22e8a15d3fb725a2f46850ae9d18491d74af
Introducing folly::Function

Summary:std::function is copy-constructible and requires that the callable that it wraps
is copy-constructible as well, which is a constraint that is often inconvenient.
In most cases when using a std::function we don't make use of its
copy-constructibility.

This diff introduces a templated type called folly::Function that is very
similar to a std::function, except it is not copy-constructible and doesn't
require the callable to be either.

Like std::function, Function is a templated type with template parameters
for return type and argument types of the callable, but not the callable's
specific type. It can store function pointers, static member function pointers,
std::function objects, std::reference_wrapper objects and arbitrary callable
types (functors) with matching return and argument types.

Much like std::function, Function will store small callables in-place, so
that no additional memory allocation is necessary. For larger callables,
Function will allocate memory on the heap.

Function has two more template parameters: firstly, an enum parameter of
type folly::FunctionMoveCtor, which defaults to NO_THROW and determines
whether no-except-movability should be guaranteed. If set to NO_THROW,
callables that are not no-except-movable will be stored on the heap, even
if they would fit into the storage area within Function.

Secondly, a size_t parameter (EmbedFunctorSize), which determines the size of
the internal callable storage. If you know the specific type of the callable you
want to store, you can set EmbedFunctorSize to sizeof(CallableType).

The original motivation of this diff was to allow to pass lambdas to
folly::Future::then that are not copy-constructible because they capture
non-copyable types, such as a promise or a unique pointer.

Another diff will shortly follow that changes folly::Future to use
folly::Function instead of std::function for callbacks, thus allowing to
pass non-copyable lambdas to folly::Future::then.

Reviewed By: fugalh

Differential Revision: D2844587

fb-gh-sync-id: 3bee2af75ef8a4eca4409aaa679cc13762cae0d0
shipit-source-id: 3bee2af75ef8a4eca4409aaa679cc13762cae0d0
folly/Function-inl.h [new file with mode: 0644]
folly/Function-pre.h [new file with mode: 0644]
folly/Function.h [new file with mode: 0644]
folly/Makefile.am
folly/test/FunctionTest.cpp [new file with mode: 0644]
folly/test/Makefile.am
folly/test/function_benchmark/benchmark_impl.cpp
folly/test/function_benchmark/benchmark_impl.h
folly/test/function_benchmark/main.cpp