Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Invoke method pointers elegantly in C++

1.00/5 (2 votes)
15 Jul 2012CPOL 23.1K  
invoke method pointer elegantly

Introduction

This tip shows an elegent way to invoke method pointers in C++.

Code

C++
//
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); 
   }
   //member vars 
   int (T::*m_fp)(int); 
   T &m_t; 
 };    
C++
 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)