HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TfFunctionRef< Sig > Class Template Reference

#include <functionRef.h>

Detailed Description

template<class Sig>
class TfFunctionRef< Sig >

This class provides a non-owning reference to a type-erased callable object with a specified signature. This is useful in cases where you want to write a function that takes a user-provided callback, and that callback is used only in the duration of the function call, and you want to keep your function's implementation out-of-line.

For technical reasons, TfFunctionRef does not support function pointers; only function objects. Internally TfFunctionRef stores a void pointer to the function object it's referencing, but C++ does not allow function pointers to be cast to void pointers. Supporting this case would increase this class's size and add complexity to its implementation. Instead, callers may wrap function pointers in lambdas to sidestep the issue.

The advantage over std::function is that TfFunctionRef is lighter-weight. Since it is non-owning, it guarantees no heap allocation; a possibility with std::function. The cost to call a TfFunctionRef is an indirect function call.

For example:

// widgetUtil.h ////////////////////////////////
class WidgetUtil
{
template <class WidgetPredicate>
bool AnyWidgetsMatch(WidgetPredicate const &predicate) {
return _AnyWidgetsMatchImpl(predRef);
}
private:
bool _AnyWidgetsMatchImpl(
TfFunctionRef<bool (Widget const &)> const &pred);
};
// widgetUtil.cpp //////////////////////////////
#include "widgetUtil.h"
bool WidgetUtil::_AnyWidgetsMatchImpl(
TfFunctionRef<bool (Widget const &)> const &pred)
{
for (Widget const &widget: GetAllTheWidgets()) {
if (pred(widget)) {
return true;
}
}
return false;
}

Here the implementation of _AnyWidgetsMatchImpl is kept out-of-line, callers can pass their own function objects for the predicate, there is no heap allocation, and the cost to invoke the predicate in the implementation is just the cost of calling a function pointer.

Definition at line 36 of file functionRef.h.


The documentation for this class was generated from the following file: