I am trying to write a templated method that will accept a member function pointer as an argument.
Here is an example class, including my latest attempt to write said template method:
class MyClass
{
public:
int myMethod() { return 1; }
template<typename T>
T call(std::function<T(MyClass*)> m)
{
return m(this);
}
};
My goal is to be able to do the following (or something very similar in syntax):
MyClass m;
auto result = m.call(&MyClass::myMethod);
So far with my attempt above, I can do:
MyClass m;
std::function<int(MyClass*)> f = &MyClass::myMethod;
auto result = m.call(f);
I was surprised I was not even able to wrap that into a single line. m.call(&MyClass::myMethod)
this does not compile. Why?
I am sure there is a way to get the behaviour I want, so any help would be much appreciated!
Apparently it cannot deduce T
(template parameter from a very deduced ctor argument).
If your goal is to simply do it in one call you can change method definition to something like
template<class F> auto call(F &&f) {
return std::invoke(std::forward<F>(f), this);
}