• Sven Over's avatar
    Introducing folly::Function · 08a67734
    Sven Over authored
    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
    08a67734
Function-inl.h 17.5 KB