16.4. Function Objects

Many Standard Library algorithms allow you to pass a function pointer into the algorithm to help the algorithm perform its task. For example, the binary_search algorithm that we discussed in Section 16.3.6 is overloaded with a version that requires as its fourth parameter a function pointer that takes two arguments and returns a bool value. The algorithm uses this function to compare the search key to an element in the collection. The function returns true if the search key and element being compared are equal; otherwise, the function returns false. This enables binary_search to search a collection of elements for which the element type does not provide an overloaded equality < operator.

Any algorithm that can receive a function pointer can also receive an object of a class that overloads the function-call operator (parentheses) with a function named operator(), provided that the overloaded operator meets the requirements of the algorithm—in the case of binary_search, it must receive two arguments and return a bool. An object of such a class is known as a function object and can be used syntactically and semantically like a function or function pointer—the overloaded parentheses operator is invoked by using a function object’s name followed by parentheses containing the arguments to the function. Most algorithms can use function objects and functions interchangeably. As you’ll learn in Section 16.5, C++11’s lambda expressions can also be used where function pointers and function objects are used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.242.253