Derive-C
Loading...
Searching...
No Matches
trampoline.hpp
Go to the documentation of this file.
1#pragma once
2#include <type_traits>
3#include <stdexcept>
4
5template<typename T>
7
8template<typename C, typename M>
9struct member_pointer_class<M C::*> {
10 using type = C;
11};
12
13template<typename T>
15
20template<auto* Function, auto MockFunction>
22public:
23 using FunctionLocationType = decltype(Function);
24 using FunctionPtrType = std::remove_pointer_t<FunctionLocationType>;
25 using MockFunctionType = decltype(MockFunction);
27
28 static inline FunctionLocationType func = Function;
29 static constexpr MockFunctionType mockFunc = MockFunction;
30 static inline FunctionPtrType realFunc = *func;
31 static inline MockType* sMock = nullptr;
32
33 template<typename... Args>
34 static auto trampolineImpl(Args... args) -> decltype((std::declval<MockType*>()->*mockFunc)(args...)) {
35 return (sMock->*mockFunc)(args...);
36 }
37
38 explicit Trampoline(MockType* mock) : mMock(*mock) {
39 if (sMock != nullptr) {
40 throw std::runtime_error("Trampoline already in use");
41 }
42 sMock = &mMock;
43 Enable();
44 }
45
46 void Disable() {
47 CheckOwnership();
48 *func = realFunc;
49 }
50
51 void Enable() {
52 CheckOwnership();
54 }
55
57 *func = realFunc;
58 sMock = nullptr;
59 }
60
61private:
62 void CheckOwnership() {
63 if (sMock != &mMock) {
64 throw std::runtime_error("Trampoline not owned by this instance");
65 }
66 }
67
68 MockType& mMock;
69 static_assert(std::is_member_function_pointer_v<MockFunctionType>);
70 static_assert(std::is_function_v<std::remove_pointer_t<FunctionPtrType>>);
71};
Trampoline(MockType *mock)
decltype(Function) FunctionLocationType
decltype(MockFunction) MockFunctionType
void Disable()
static constexpr MockFunctionType mockFunc
void Enable()
static auto trampolineImpl(Args... args) -> decltype((std::declval< MockType * >() -> *mockFunc)(args...))
std::remove_pointer_t< FunctionLocationType > FunctionPtrType
static FunctionPtrType realFunc
member_pointer_class_t< MockFunctionType > MockType
static FunctionLocationType func
static MockType * sMock
typename member_pointer_class< T >::type member_pointer_class_t