Delegate Manual

About

Cinema 4D R19 introduced the maxon::Delegate class. Such a delegate can be used instead of a callback function. The class is defined in the delegate.h header file.

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 function.

// 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<Bool(Int32)>& progress);

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.
void LongRunningTask(const maxon::Delegate<Bool(Int32)>& progress)
{
for (Int32 i = 0; i < 100; ++i)
{
const Bool res = progress(i);
if (!res)
return;
}
}

Usage

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

// This example shows various ways to define the callback declared with maxon::Delegate.
// define a lambda directly
LongRunningTask([](Int32 p)
{
if (p > 50)
return false;
return true;
});
// pass a lambda object
auto lambda = [](Int32 p)
{
if (p > 66)
return false;
return true;
};
LongRunningTask(lambda);
// use maxon::Delegate object
const maxon::Delegate<Bool(Int32)> function(&SomeFunction);
LongRunningTask(function);
// or just give a function pointer
LongRunningTask(&SomeFunction);

Further Reading