I've been working on making a small delegate template exercise to 1.) better myself, 2.) better understand template metaprogramming, and to 3.) possibly even use delegates for some event-driven programming (as I do not have access to standard libraries). According to this answer, something like the following can be implemented for functions:
template <typename T, typename R, typename ...Args>
R proxycall(T & obj, R (T::*mf)(Args...), Args &&... args)
{
return (obj.*mf)(args...);
}
proxycall(myobj, &MyObj::func);
It seems as if the compiler can figure out the return type, class type, and parameter types just by passing myobj
and &MyObj::func
into the template. Can the same method as above be used to create a delegate class (class that stores both a reference to an object and a pointer-to-member function)?
Delegate d(myobj, &MyObj::func); /* Preferred */
or
Delegate<myobj, &MyObj::func> d; /* Ok */
The following class is my Delegate class and it has the unfortunate side-effect of having to specify the ReturnType
and the types of the Parameters
in the corresponding member function. As I see above, the compiler can figure that stuff out. So, how can I have the compiler help me out?
template <class Class, typename ReturnType, typename ... Parameters>
class Delegate {
public:
typedef ReturnType (Class::*Method)(Parameters ... params);
Delegate(Class& ref, Method m) : obj(ref), method(m) {}
ReturnType operator()(Parameters ... params) { return (obj.*method)(params...); }
ReturnType Invoke(Parameters ... params) { return operator()(params...); }
private:
Class& obj;
Method method;
};
/* Usage */
Delegate<MyObj, void> d(myobj, &MyObj::func);
^^^^^^^^^^^
ick