Top of document
©Copyright 1999 Rogue Wave Software

Negators and Binders

Negators and binders are function adaptors that are used to build new function objects out of existing function objects. Almost always, these are applied to functions as part of the process of building an argument list prior to invoking yet another function or generic algorithm.

The negators not1() and not2() take a unary and a binary predicate function object, respectively, and create a new function object that will yield the complement of the original. For example, using the widget tester function object defined in the previous section, the function object

   not2(WidgetTester())
 

yields a binary predicate which takes exactly the same arguments as the widget tester, and which is true when the corresponding widget tester would be false, and false otherwise. Negators work only with function objects defined as subclasses of the classes unary_function and binary_function, given earlier.

A Hot Idea

A binder takes a two-argument function, and binds either the first or second argument to a specific value, thereby yielding a one-argument function. The underlying function must be a subclass of class binary_function. The binder bind1st() binds the first argument, while the binder bind2nd() binds the second.

For example, the binder bind2nd(greater<int>(), 5) creates a function object that tests for being larger than 5. This could be used in the following, which yields an iterator representing the first value in a list larger than 5:

list<int>::iterator where = find_if(aList.begin(), aList.end(),
            bind2nd(greater<int>(), 5));
 

Combining a binder and a negator, we can create a function that is true if the argument is divisible by 3, and false otherwise. This can be used to remove all the multiples of 3 from a list.

list<int>::iterator where = remove_if (aList.begin(), aList.end(),
            not1(bind2nd(modulus<int>(), 3)));
 

A binder is used to tie the widget number of a call to the binary function WidgetTester(), yielding a one-argument function that takes only a widget as argument. This is used to find the first widget that matches the given widget type:

list<Widget>::iterator wehave = 
    find_if(on_hand.begin(), on_hand.end(), 
       bind2nd(WidgetTester(), wid));

Top of document