action_s utility

This commit is contained in:
Matthew Kennedy 2024-01-05 14:53:54 -08:00 committed by rusefillc
parent 0ee0e05644
commit d4105657c5
1 changed files with 20 additions and 2 deletions

View File

@ -8,6 +8,24 @@
typedef void (*schfunc_t)(void *); typedef void (*schfunc_t)(void *);
template<class To, class From>
std::enable_if_t<
sizeof(To) == sizeof(From) &&
std::is_trivially_copyable_v<From> &&
std::is_trivially_copyable_v<To>,
To>
// constexpr support needs compiler magic
bit_cast(const From& src) noexcept
{
static_assert(std::is_trivially_constructible_v<To>,
"This implementation additionally requires "
"destination type to be trivially constructible");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
class action_s { class action_s {
public: public:
// Default constructor constructs null action (ie, implicit bool conversion returns false) // Default constructor constructs null action (ie, implicit bool conversion returns false)
@ -16,13 +34,13 @@ public:
// Allow implicit conversion from schfunc_t to action_s // Allow implicit conversion from schfunc_t to action_s
action_s(schfunc_t callback) : action_s(callback, nullptr) { } action_s(schfunc_t callback) : action_s(callback, nullptr) { }
action_s(schfunc_t callback, void *param) : m_callback(callback), m_param(param) { } action_s(schfunc_t callback, void *param) : m_callback(callback), m_param(param) { }
template <typename TParam>
action_s(schfunc_t callback, TParam& param) : m_callback(callback), m_param(&param) { }
// Allow any function that takes a single pointer parameter, so long as param is also of the same pointer type. // Allow any function that takes a single pointer parameter, so long as param is also of the same pointer type.
// This constructor means you shouldn't ever have to cast to schfunc_t on your own. // This constructor means you shouldn't ever have to cast to schfunc_t on your own.
template <typename TArg> template <typename TArg>
action_s(void (*callback)(TArg*), TArg* param) : m_callback((schfunc_t)callback), m_param(param) { } action_s(void (*callback)(TArg*), TArg* param) : m_callback((schfunc_t)callback), m_param(param) { }
template <typename TArg>
action_s(void (*callback)(TArg), TArg param) : m_callback(bit_cast<schfunc_t>(callback)), m_param(reinterpret_cast<void*>(param)) { }
void execute(); void execute();
schfunc_t getCallback() const; schfunc_t getCallback() const;