Created
June 27, 2025 19:57
-
-
Save DrkWithT/735e49b7b3d88a452b075374b941258d to your computer and use it in GitHub Desktop.
Member Function Wrapper
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
#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