scc 2026.07
SystemC components library
defer.h
1
30#ifndef UTIL_DEFER_H
31#define UTIL_DEFER_H
32
34
37#define DEFER const auto DEFER_CAT_ID(callOnScopeExit, __LINE__) = (Util::tagClassForLambda)->*[&]()
38
39//==============================================================================
40// Implementation details follow
41
42// Helper macro to expand and concatenate macro arguments into combined identifier
43#define DEFER_CAT_ID(a, b) DEFER_CAT_ID_EXPANDED_HELPER(a, b)
44// helper macro to concatenate expanded macro arguments
45#define DEFER_CAT_ID_EXPANDED_HELPER(a, b) a##b
46
47namespace Util {
49struct TagClassForLambda {
50 constexpr TagClassForLambda() = default;
51};
52
53
55constexpr TagClassForLambda tagClassForLambda;
56
58template <class Lambda> struct CallOnScopeExit {
60
61 constexpr CallOnScopeExit(Lambda initialLambda)
62 : lambda(initialLambda)
63 , isOwner(true) {}
64
67 : lambda(other.lambda)
68 , isOwner(true) {
69 other.isOwner = false;
70 }
71
72 // ensure copy changes go only through move constructor
73 CallOnScopeExit(const CallOnScopeExit& other) = delete;
74 CallOnScopeExit& operator=(const CallOnScopeExit& other) = delete;
75
78 if(isOwner) { // condition is usually optimized away
79 lambda();
80 }
81 }
82
83private:
84 const Lambda lambda;
85 bool isOwner;
86};
87
89
91template <class Lambda> constexpr CallOnScopeExit<Lambda> operator->*(const TagClassForLambda&, Lambda lambda) {
92 return CallOnScopeExit<Lambda>(lambda);
93}
94} // namespace Util
95#endif // UTIL_DEFER_H
RAII for implementing DEFER behavior.
Definition defer.h:58
CallOnScopeExit(CallOnScopeExit &&other)
Usually optimized away due to RVO.
Definition defer.h:66
constexpr CallOnScopeExit(Lambda initialLambda)
Create RAII wrapper around Lambda.
Definition defer.h:61
~CallOnScopeExit()
Actual lambda call once CallOnScopeExit goes out of scope.
Definition defer.h:77
Helper type to trigger operator ->*.
Definition defer.h:49