Skip to content

Instantly share code, notes, and snippets.

@DrkWithT
Created June 27, 2025 19:57
Show Gist options
  • Save DrkWithT/735e49b7b3d88a452b075374b941258d to your computer and use it in GitHub Desktop.
Save DrkWithT/735e49b7b3d88a452b075374b941258d to your computer and use it in GitHub Desktop.
Member Function Wrapper
#include <print>
struct Foo {
int x;
Foo() noexcept
: x {0} {}
[[nodiscard]] int operator()() noexcept {
return ++x;
}
};
template <typename Class, typename Result, typename... Args>
class FunctorStore {
private:
using member_fn_t = Result(Class::*)(Args...);
member_fn_t m_fp;
public:
constexpr FunctorStore() noexcept
: m_fp {nullptr} {}
explicit constexpr FunctorStore(member_fn_t fp_) noexcept
: m_fp {fp_} {}
template <typename... Args2>
[[nodiscard]] Result operator()(Class* self, Args2&&... args2) noexcept(noexcept((self->*m_fp)(args2...))) {
return (self->*m_fp)(args2...);
}
};
int main() {
Foo f;
FunctorStore store_fun {&Foo::operator()};
std::print("answer = {}\n", store_fun(&f));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment