Function taking pointer-to-method regardless of constness
The short answer is, don't implement this yourself, it has already been done for you in the form of std::invoke
:
#include <functional>
struct A {
void foo(int x);
void bar(int x) const;
};
void example() {
A a;
std::invoke(&A::foo, a, 3);
std::invoke(&A::bar, a, 3);
}
Seeing that you have added a C++14 tag in retrospect, the documentation of std::invoke
has a sample implementation which you can use in your project.
Here's a C++14 alternative without using std::function
.
what I want to ultimately achieve is pass a 3rd parameter, a data buffer from which method arguments will be extracted - hence the template function to handle it as generically as possible
What you use at the call site will be perfectly forwarded here:
template<typename Class, typename Func, typename... Args>
decltype(auto) callMethod_impl(Class& object, Func method, Args&&... args) {
return (object.*method)(std::forward<Args>(args)...);
}
template<typename Ret, typename Class, typename... Us, typename... Args>
Ret callMethod(Class& object, Ret(Class::*method)(Us...), Args&&... args) {
return callMethod_impl(object, method, std::forward<Args>(args)...);
}
template<typename Ret, typename Class, typename... Us, typename... Args>
Ret callMethod(const Class& object, Ret(Class::*method)(Us...) const, Args&&... args) {
return callMethod_impl(object, method, std::forward<Args>(args)...);
}
Demo
If you need Ret
in callMethod_impl
, just add it as a template parameter and call it like callMethod_impl<Ret>(...)
from the callMethod
overloads (Demo).