Skip to content

Instantly share code, notes, and snippets.

@ziap
Last active May 5, 2024 07:54
Show Gist options
  • Save ziap/1633ac30db4eb1ecf17f745811229733 to your computer and use it in GitHub Desktop.
Save ziap/1633ac30db4eb1ecf17f745811229733 to your computer and use it in GitHub Desktop.
Fat pointer based polymorphic function wrapper, `std::function` alternative
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