Last active
November 30, 2022 12:13
-
-
Save isc30/fab67e5956fe8f2097bed84ebc42c1e8 to your computer and use it in GitHub Desktop.
template-based wrapper for any callable with signature + metadata traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <type_traits> | |
#include <functional> | |
template<typename TCallable, typename TSignature> | |
constexpr bool is_callable_as_v = std::is_constructible<std::function<TSignature>, TCallable>::value; | |
template< | |
typename TCallable, | |
typename TSignature, | |
typename = std::enable_if_t<is_callable_as_v<TCallable, TSignature>>> | |
using Callable = TCallable; | |
template<typename TCallable> | |
struct CallableMetadata | |
: CallableMetadata<decltype(&TCallable::operator())> | |
{ | |
}; | |
template<class TClass, typename TReturn, typename... TArgs> | |
struct CallableMetadata<TReturn(TClass::*)(TArgs...)> | |
{ | |
using class_t = TClass; | |
using return_t = TReturn; | |
using args_tuple_t = std::tuple<TArgs...>; | |
using ptr_t = TReturn(*)(TArgs...); | |
// Beware! this function makes a copy of the closure! and of the arguments when called! | |
static ptr_t generatePointer(const TClass& closure) | |
{ | |
static TClass staticClosureCopy = closure; | |
return [](TArgs... args) | |
{ | |
return staticClosureCopy(args...); | |
}; | |
} | |
}; | |
template<class TClass, typename TReturn, typename... TArgs> | |
struct CallableMetadata<TReturn(TClass::*)(TArgs...) const> | |
{ | |
using class_t = TClass; | |
using return_t = TReturn; | |
using args_tuple_t = std::tuple<TArgs...>; | |
using ptr_t = TReturn(*)(TArgs...) const; | |
// Beware! this function makes a copy of the closure! and of the arguments when called! | |
static ptr_t generatePointer(const TClass& closure) | |
{ | |
static TClass staticClosureCopy = closure; | |
return [](TArgs... args) | |
{ | |
return staticClosureCopy(args...); | |
}; | |
} | |
}; | |
// Beware! this function makes a copy of the closure! and of the arguments when called! | |
template<typename TCallable> | |
auto* callableToPointer(const TCallable& callable) | |
{ | |
return CallableMetadata<TCallable>::generatePointer(callable); | |
} |
I have no idea tbh, i wrote this a long time ago
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clang 12 is complaining:
on line 47
I removed the "const" qualifier, and it seems to work, but maybe I am missing something?