Last active
May 5, 2024 07:54
-
-
Save ziap/1633ac30db4eb1ecf17f745811229733 to your computer and use it in GitHub Desktop.
Fat pointer based polymorphic function wrapper, `std::function` alternative
This file contains hidden or 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
template<class> | |
class Function {}; | |
template<class R, class ...Args> | |
class Function<R(Args...)> { | |
private: | |
template<class F> | |
static R type_erase(const void *fn, Args... args) { | |
return (*(const F*)fn)(args...); | |
} | |
const void *data; | |
R (*vcall)(const void*, Args...); | |
public: | |
template<class F> | |
Function(const F &f) : data{(const void*)&f}, vcall{type_erase<F>} {} | |
template<class F> | |
Function(const F &&f) : vcall{type_erase<F>} { | |
static F fn_static = f; | |
data = &fn_static; | |
} | |
Function(const Function &f) : data{f.data}, vcall{f.call_fn} {}; | |
R operator()(Args... args) const { | |
return vcall(data, args...); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment