Lumiera  0.pre.03
»edityourfreedom«
function-erasure.hpp File Reference

Go to the source code of this file.

Description

Generic holder for functor objects, concealing the concrete function type.

When working with generic function objects and function pointers typed to arbitrary signatures, often there is the necessity to hold onto such a functor while hiding the actual signature behind an common interface ("type erasure"). The usual solution based on subclassing has the downside of requiring separate storage for the concrete functor object, which might become problematic when dealing with lots of functor objects.

Especially when dealing with std::function objects, all of the type differences are actually encoded into 3 internal pointers, thus yielding the same size for all various types of functors. Building on this observation, we can create an common container object to store the varying functors inline, while hiding the actual signature.

There remains the problem of re-accessing the concrete functor later on. As C++ has only rudimental introspection capabilities, we can only rely on the usage context to provide the correct function signature; only when using a virtual function for the re-access, we can perform at least a runtime-check.

Thus there are various flavours for actually implementing this idea, and picking a suitable implementation depends largely on the context. Thus we provide a common frontend for access and expect the client code to pick a suitable implementation policy.

See also
control::Mutation usage example
function-erasure-test.cpp

Definition in file function-erasure.hpp.

#include "lib/util.hpp"
#include "lib/error.hpp"
#include "lib/opaque-holder.hpp"
#include "lib/functor-util.hpp"
#include <functional>

Classes

struct  FunErasure< FH >
 Generic wrapper carrying a function object while hiding the actual function signature. More...
 
class  StoreFunction
 Policy for FunErasure: store an embedded std::function Using this policy allows to store arbitrary complex functor objects embedded within a neutral container and retrieving them later type-safe. More...
 
class  StoreFunPtr
 Policy for FunErasure: store a bare function pointer. More...
 
class  StoreUncheckedFunPtr
 Policy for FunErasure: store an unchecked bare function pointer. More...
 

Typedefs

typedef lib::InPlaceAnyHolder< sizeof(FunVoid), lib::InPlaceAnyHolder_unrelatedTypesFunHolder
 
typedef lib::InPlaceAnyHolder< sizeof(void *), lib::InPlaceAnyHolder_unrelatedTypesFunPtrHolder
 
typedef function< void(void)> FunVoid
 

Namespaces

 lib
 Implementation namespace for support and library code.
 
 lib::meta