Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Jan 13, 1999

Prefer Function Objects to Function Pointers

Passing a function pointer is a common practice in event-driven systems, whereby a callback routine is invoked through a pointer. C++, however, offers a better alternative to function pointers: function objects. Using a function object instead of a pointer offers several advantages. First, your code is more resilient to changes, since the object containing the function can be modified without affecting its users. In addition, compilers can inline a function object, thereby enhancing performance even further. But perhaps the most compelling argument in favor of function objects is their genericity. A function object can embody a generic algorithm by means of a member template, something not easily accomplished with ordinary function pointers. In the following example, a function object implements a generic negation operator:
 
#include <iostream> 
#include <vector>
using namespace std;

class negate {
  public : template < class T > T operator()  (T t) const { return -t;} //generic negation operator 
};
void callback(int n, const negate& neg) { //pass a function object rather than a function pointer
  n = neg(n);  // invoke the overloaded () operator to negate n
  cout << n;
}
void main() 
{
 callback(5, negate() ); //output -5
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap