src/nano/nano_function.hpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #ifndef MODEL_NANO_FUNCTION_HPP | ||
| 2 | #define MODEL_NANO_FUNCTION_HPP | ||
| 3 | |||
| 4 | #include <cstdint> | ||
| 5 | #include <array> | ||
| 6 | |||
| 7 | namespace Nano { | ||
| 8 | |||
| 9 | using DelegateKey = std::array<std::uintptr_t, 2>; | ||
| 10 | |||
| 11 | template <typename RT> | ||
| 12 | class Function; | ||
| 13 | template <typename RT, typename... Args> | ||
| 14 | class Function<RT(Args...)> | ||
| 15 | { | ||
| 16 | using Thunk = RT (*)(void*, Args...); | ||
| 17 | |||
| 18 | friend class Observer; | ||
| 19 | |||
| 20 | void* m_this_ptr; // instance pointer | ||
| 21 | Thunk m_stub_ptr; // free function pointer | ||
| 22 | |||
| 23 | 733891 | Function(void* this_ptr, Thunk stub_ptr) : m_this_ptr(this_ptr), m_stub_ptr(stub_ptr) {} | |
| 24 | |||
| 25 | 1693455 | Function(DelegateKey delegate_key) : m_this_ptr(reinterpret_cast<void*>(delegate_key[0])), m_stub_ptr(reinterpret_cast<Thunk>(delegate_key[1])) {} | |
| 26 | |||
| 27 | public: | ||
| 28 | template <RT (*fun_ptr)(Args...)> | ||
| 29 | static inline Function bind() { | ||
| 30 | return {nullptr, [](void* /*NULL*/, Args... args) { return (*fun_ptr)(std::forward<Args>(args)...); }}; | ||
| 31 | } | ||
| 32 | template <typename T, RT (T::*mem_ptr)(Args...)> | ||
| 33 | 733891 | static inline Function bind(T* pointer) { | |
| 34 | 1160249 | return {pointer, [](void* this_ptr, Args... args) { return (static_cast<T*>(this_ptr)->*mem_ptr)(std::forward<Args>(args)...); }}; | |
| 35 | } | ||
| 36 | template <typename T, RT (T::*mem_ptr)(Args...) const> | ||
| 37 | static inline Function bind(T* pointer) { | ||
| 38 | return {pointer, [](void* this_ptr, Args... args) { return (static_cast<T*>(this_ptr)->*mem_ptr)(std::forward<Args>(args)...); }}; | ||
| 39 | } | ||
| 40 | template <typename L> | ||
| 41 | static inline Function bind(L* pointer) { | ||
| 42 | return {pointer, [](void* this_ptr, Args... args) { return (static_cast<L*>(this_ptr)->operator()(std::forward<Args>(args)...)); }}; | ||
| 43 | } | ||
| 44 | 733891 | inline operator DelegateKey() const { | |
| 45 | 733891 | return {{reinterpret_cast<std::uintptr_t>(m_this_ptr), reinterpret_cast<std::uintptr_t>(m_stub_ptr)}}; | |
| 46 | } | ||
| 47 | template <typename... Uref> | ||
| 48 | 1693455 | inline RT operator()(Uref&&... args) { | |
| 49 | 1693455 | return (*m_stub_ptr)(m_this_ptr, std::forward<Uref>(args)...); | |
| 50 | } | ||
| 51 | }; | ||
| 52 | |||
| 53 | } // namespace Nano | ||
| 54 | |||
| 55 | #endif // MODEL_NANO_FUNCTION_HPP | ||
| 56 |