Delegates

About

A maxon::Delegate is used to define a callback function.

Declaration

A function that provides the callback simply defines a maxon::Delegate argument. The maxon::Delegate class template defines both the return value and argument types of the callback functions.

// This example declares a global function. maxon::Delegate is used to define a callback function.
//----------------------------------------------------------------------------------------
// Performs a long running task.
// @param[in] progress Callback which is triggered during the task. Return false to stop the execution of the task.
//----------------------------------------------------------------------------------------
static void LongRunningTask(const maxon::Delegate<maxon::Bool(maxon::Int32)>& progress);
Definition: delegate.h:240
bool Bool
boolean type, possible values are only false/true, 8 bit
Definition: apibase.h:181
int32_t Int32
32 bit signed integer datatype.
Definition: apibase.h:176

maxon::ValueReceiver is a template for a generic delegate function.

Invocation

Within a function the maxon::Delegate argument can be used like an ordinary function pointer.

// This example defines a function. The given maxon::Delegate object
// is invoked to check if the function should continue.
static void LongRunningTask(const maxon::Delegate<maxon::Bool(maxon::Int32)>& progress)
{
for (maxon::Int32 i = 0; i < 100; ++i)
{
const maxon::Bool res = progress(i);
if (!res)
return;
}
}
Py_ssize_t i
Definition: abstract.h:645
Py_UCS4 * res
Definition: unicodeobject.h:1113

Usage

There are multiple ways to define the actual callback. It is possible to define the lambda directly, use a lambda object, use a maxon::Delegate object or just use a simple function pointer.

Note
A delegate can be defined using a lambda function. This lambda function must not use data that can only be moved. This is because at some point the delegate object might be copied.
// This example shows various ways to define the callback declared with maxon::Delegate.
// define the lambda directly
LongRunningTask([](maxon::Int32 p)
{
DiagnosticOutput("Percentage: @", p);
if (p > 50)
return false;
return true;
});
// use a lambda object
auto lambda = [](maxon::Int32 p)
{
DiagnosticOutput("Percentage: @", p);
if (p > 66)
return false;
return true;
};
LongRunningTask(lambda);
// use maxon::Delegate object
const maxon::Delegate<maxon::Bool(maxon::Int32)> maxonDelegate(SomeFunction);
LongRunningTask(maxonDelegate);
// or just a function pointer
LongRunningTask(SomeFunction);
unsigned char * p
Definition: floatobject.h:87
#define DiagnosticOutput(formatString,...)
Definition: debugdiagnostics.h:176

Further Reading