Introduction
This tip shows an elegent way to invoke method pointers in C++.
Code
template <class T>
class MemFnPtr
{
public:
MemFnPtr(int (T::*fp)(int), T &t) : m_fp(fp), m_t(t)
{
}
int Fn(int n)
{
return ((m_t).*(m_fp))(n);
}
int (T::*m_fp)(int);
T &m_t;
};
int main()
{
A a_obj;
MemFnPtr<A> fp_a(&A::Func1, a_obj);
cout << fp_a.Fn(10) << endl;
return 0;
}
History
Tip submitted : 16th July, 2012