|
-
February 28th, 2003, 05:24 PM
#1
operator()
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?
-
February 28th, 2003, 06:27 PM
#2
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:
Code:
#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
-
February 28th, 2003, 06:52 PM
#3
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().
Code:
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|