Click to See Complete Forum and Search --> : operator()


stober
February 28th, 2003, 04:24 PM
Found your FAQ about 2d arrays -- really liked that template class. One of the comments was to suggest implemting () operator. What does that operator do?? I understand what the [] operator does, but have no clue about the () operator. Can you give me a simple example?

Gabriel Fleseriu
February 28th, 2003, 05:27 PM
The operator () is the function call operator. A class that defines this operator is also called a "functor" because it behaves simmilary to a function. But, being a class (i.e. actually an object) it can "retain" state information from one "call" to another and much more.

Example:

#include <iostream>

class functor
{
public:
functor(int i):i_(i){}
void operator ()(int j){std::cout<<i_+j;}
private:
int i_;
};

int main()
{
functor f(1); // ctor; f.i_==1
f(3); // will print 4
return 0;
}


The example is a naïve one, I know. Also note that I didn't compile this code :)

Paul McKenzie
February 28th, 2003, 05:52 PM
To add to Gabriels explanantion, operator() is the reason why you can pass a function pointer as well as a function object to many STL functions.

Note that algorithms such as std::sort take a function object and a "normal" function pointer as an optional third argument. The reason why this is possible is that the syntax to call a function through a pointer is exactly the same as calling an object's operator().

void (*foo)(int);
struct foo2
{
void operator()(int n) { }
};
//...
foo(); // calls a function pointed to by foo.
//...
foo2 sFoo;
sFoo(); // calls sFoo's operator()

Therefore when you write a template function or class, and you expect a function pointer as one of the template args, your template function will more than likely work automatically with function objects as well as function pointers.

Regards,

Paul McKenzie