Chapter 39. Virtual inheritance-based function callable objects

Index

Virtual inheritance-based callables as reference-counted objects
Using callable objects to implement the callback design pattern
x::invoke_callbacks() helpers
Single execution thread callback container
Lambda weak pointer captures
#include <x/functional.H>

int method(const x::function<int(const char *)> &func)
{
    return func("Hello world");
}

auto closure=x::make_function<int(const char *)>([]
             (const char *arg)
             {
                 return strlen(arg);
             })

int n=method(closure);

This is a mechanism for implementing function objects for type-erasing lambdas which uses virtual inheritance instead of heap allocation, like std::function. x::function<return_type(Args...)> is a function object that implements an operator() that takes Args... parameters and returns a return_type, like std::function. x::make_function<return_type(Args...)>() takes a functor parameter, and returns a subclass of x::function<return_type(Args...)> that implements the operator() by invoking the functor.

The two main ways to use x::function are:

  1. Call x::make_function<return_type(Args...)>() and pass its return value to a function that takes a const x::function<return_type(Args...)> & parameter.

  2. Call x::make_function<return_type(Args...)>() and store its return value in an auto variable, that's subsequently passed as a const x::function<return_type(Args...)> & function parameter.

Virtual inheritance-based callables as reference-counted objects

x::functionref and x::functionptr provide a reference-counted wrapper for an x::function<return_type(Args...)>. This implements very similar semantics as std::function, but with all the reference-counted goodies:

#include <x/functionalrefptr.H>

int method(const x::function<int(const char *)> &func)
{
    return func("Hello world");
}

// ...

x::functionref<int(const char *)> auto closure=[]
             (const char *arg)
             {
                 return strlen(arg);
             };

    x::function<int(const char *)> &fr = *f;

    return method(fr) + f("!");
}

x::functionref inherits from a reference to an obj that also inherits from an x::function.