Google
 

5/10/07

function object or functors.

Defining a Function Object
By Danny Kalev

from the following link:
http://www.inquiry.com/techtips/cpp_pro/10min/10min0100.asp

Although pointers to functions are widely used for implementing function callbacks, C++ offers a significantly superior alternative to them, namely function objects. Function objects (also called "functors") are ordinary class objects that overload the () operator. Thus, syntactically, they behave like ordinary functions.

There are several advantages in using a function object instead of a pointer to function. First, they are more resilient to design changes because the object can be modified internally without changing its external interface. A function object can also have data members that store the result of a previous call. When using ordinary functions, you need to store the result of a previous call in a global or a local static variable. However, global and local static variables have some undesirable characteristics. Finally, compilers can inline a call made through a function object, thereby enhancing performance even further. In contrast, it is nearly impossible to inline a function call made through a pointer.

This solution will show how to define and use a function object that implements a negation operation. The first step consists of declaring an ordinary class and overloading the () operator:

class Negate
{
public:
int operator() (int n) { return -n;}
};

The overloaded () might look a bit confusing because it has two pairs of parentheses. Remember that the first pair is always empty because it serves as the operator's name; the parameter list appears in the second pair of parentheses. Unlike other overloaded operators, whose number of parameters is fixed, the overloaded () operator may take any number of parameters.

Because the built-in negation operator is unary (it takes only a single operand), our overloaded () operator also takes a single parameter. The return type is identical to the parameter's type—int, in our example. The function body is trivial; it simply returns the negated argument.

Using the Function Object
We now define a function named Callback() to test our function object. Callback() takes two arguments: an int and a reference to Negate. Callback() treats neg, the function object, as if it were a function's name:

#include
using std::cout;

void Callback(int n, Negate & neg)
{
int val = neg(n); //1 invoke overloaded ()
cout << val =" neg.operator()(n);" t=""> T operator() (T t) const {return -t;}
};

int main()
{
GenericNegate negate;
cout<<> or less<> to sort() to force a descending or ascending sorting order, respectively:

#include // for greater<> and less<>
#include //for sort()
#include
using namespace std;

int main()
{
vector vi;
//..fill vector
sort(vi.begin(), vi.end(), greater() );//descending
sort(vi.begin(), vi.end(), less() ); //ascending
}



No comments: