dcsimg
Login | Register   
LinkedIn
Google+
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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
Thanks for your registration, follow us on our social networks to keep up-to-date