Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of operator()?

What is the meaning of operator() in C++? I see that is often used for "functors," or function objects such as comparators. But then how are such functions called? Is it useful in other situations? And how many parameters can I declare for such an operator? E.g., is the following acceptable?

bool operator() (Foo f, Baz b, Quz q, Oik o) {...}
like image 475
Nels Beckman Avatar asked Dec 17 '22 15:12

Nels Beckman


1 Answers

Let's say you have a function object class, Func, with operator() defined. If you have an instance of that class, you can simply place parentheses after the expression referring to that instance:

Func myFunc;
myFunc(); // Calls the operator() member function

As an example from the standard library, we can look at std::less which is a binary function object:

std::less<int> myLess; // Create an instance of the function object
std::cout << myLess(5, 6) << std::endl; // Is 5 less than 6?

Another common use for operator() is when creating a Matrix class. You may define T& Matrix::operator()(int,int) to retrieve an element from the matrix like myMatrix(1,2).

The number of parameters that operator() can take is the same as any other function. This is implementation-defined though. The recommended minimum number of arguments that your implementation should allow is 256 (given in Annex B of the standard).


operator()'s lookup is defined in the standard (ISO/IEC 14882:2003 §13.3.1.1.2) by:

If the primary-expression E in the function call syntax evaluates to a class object of type "cv T", then the set of candidate functions includes at least the function call operators of T. The function call operators of T are obtained by ordinary lookup of the name operator() in the context of (E).operator().

Translation: If you make a function call using the syntax expression() and the expression before the parentheses evaluates to an instance of a class, then add the objects operator() member function to the list of candidate functions that may be called.

like image 153
Joseph Mansfield Avatar answered Dec 31 '22 15:12

Joseph Mansfield