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

This class provides a non-owning reference to a type-erased callable object with a specified signature. More...

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.

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: