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


advertisement
 

Use the std::tr1::function Class to Generalize Callbacks-4 : Page 4


advertisement
Higher Order Functions
Higher-order functions are a key concept in the functional programming paradigm. A higher order function accepts functions as its argument and returns a function as its result. std::tr1::function facilitates the implementation of higher order functions. Consider a calculator program that accepts an operation code from the user and returns a matching function in the form of a std::tr1::function object:

#include <functional> using std::tr1::function; function <int (int x, int y)> //return type get_operation(char opcode) { switch (opcode) { case '+': return std::plus<int>(); case '-': return std::minus<int>(); case '/': return std::divides<int>(); case '*': return std::multiplies<int>(); case '%': return std::modulus<int>(); default: return function<int (int x, int y)>(); } }

The use of std::tr1::function has two advantages: a function object has a state, unlike a bare pointer. Additionally, it simplifies the syntax considerably.

A Useful Improvement
std::tr1::function provides a generic, standardized and intuitive mechanism for encapsulating the low-level details of callbacks. As opposed to typedefs, virtual function overriding and classic function objects, this new class has relaxed type matching rules, thus offering more flexibility while reducing the amount of boilerplate code required by other encapsulation techniques.





Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap