www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

STL Tutorial - Lesson 4: Function Objects

Introduction

by John Kopp

Support this site at no cost to you

Many of the generic algorithms and a few methods of some of the container classes accept an additional parameter that can modify the behavior of these functions in useful ways. This additional parameter is a function object or an ordinary function. A function object is an instance of a class that has the function operator, operator(), overloaded. How to write function objects and the advantages of using function objects over ordinary functions will be discussed in this less. Function objects can greatly extend the usefulness of the generic algorithms.

Although we will examine how to define our own functions and function objects, the standard library contains sets of arithmetic, relational and logical function objects that are used more frequently. These built-in function objects fall into three general categories: arithmetic, relational and logical. We will examine each.

Extending further the use of function objects are adapters. Adapters are used to modify the behavior of function objects and predicates, in general. A predicate is a function or function object that accepts several arguments and returns a boolean, or true/false, result. Adapters can turn binary (two argument) function objects into unary (one argument). They can also negate, or reverse the sense of, a function object.

Previous Page       Next Page