This document is for a version of USD that is under development. See this page for the current release.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
functionRef.h
1//
2// Copyright 2020 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_FUNCTION_REF_H
8#define PXR_BASE_TF_FUNCTION_REF_H
9
10#include "pxr/pxr.h"
11
12#include <memory>
13#include <type_traits>
14#include <utility>
15
16PXR_NAMESPACE_OPEN_SCOPE
17
18template <class Sig>
20
81template <class Ret, class... Args>
82class TfFunctionRef<Ret (Args...)>
83{
84 // Type trait to detect when an argument is a potentially cv-qualified
85 // TfFunctionRef. This is used to disable the generic constructor and
86 // assignment operator so that TfFunctionRef arguments are copied rather
87 // than forming TfFunctionRefs pointing to TfFunctionRefs.
88 template <typename Fn>
89 using _IsFunctionRef = std::is_same<
90 std::remove_cv_t<std::remove_reference_t<Fn>>, TfFunctionRef>;
91
92public:
94 template <class Fn, class = std::enable_if_t<!_IsFunctionRef<Fn>::value>>
95 constexpr TfFunctionRef(Fn &fn) noexcept
96 : _fn(static_cast<void const *>(std::addressof(fn)))
97 , _invoke(_InvokeFn<Fn>) {}
98
101 TfFunctionRef(TfFunctionRef const &rhs) noexcept = default;
102
106 operator=(TfFunctionRef const &rhs) noexcept = default;
107
109 template <class Fn>
110 std::enable_if_t<!_IsFunctionRef<Fn>::value,
112 operator=(Fn &fn) noexcept {
113 *this = TfFunctionRef(fn);
114 return *this;
115 }
116
119 void swap(TfFunctionRef &other) noexcept {
120 std::swap(_fn, other._fn);
121 std::swap(_invoke, other._invoke);
122 }
123
125 inline Ret operator()(Args... args) const {
126 return _invoke(_fn, std::forward<Args>(args)...);
127 }
128
129private:
130 template <class Fn>
131 static Ret _InvokeFn(void const *fn, Args...args) {
132 using FnPtr = typename std::add_pointer<
133 typename std::add_const<Fn>::type>::type;
134 return (*static_cast<FnPtr>(fn))(std::forward<Args>(args)...);
135 }
136
137 void const *_fn;
138 Ret (*_invoke)(void const *, Args...);
139};
140
142template <class Sig>
143inline void
145{
146 lhs.swap(rhs);
147}
148
149PXR_NAMESPACE_CLOSE_SCOPE
150
151#endif // PXR_BASE_TF_FUNCTION_REF_H
This class provides a non-owning reference to a type-erased callable object with a specified signatur...
Definition: functionRef.h:19