Function call statement

Possible duplicates:
C ++ Functors - and their use.
Why redefine operator ()?

I saw the use of operator() in STL containers, but what is it and when do you use it?

+4
source share
2 answers

This operator turns your object into a functor. Here is a good example of how this is done.

The following example demonstrates how to implement a class for use as a functor:

 #include <iostream> struct Multiply { double operator()( const double v1, const double v2 ) const { return v1 * v2; } }; int main () { const double v1 = 3.3; const double v2 = 2.0; Multiply m; std::cout << v1 << " * " << v2 << " = " << m( v1, v2 ) << std::endl; } 
+6
source

This makes the object "callable" as a function. Unlike a function, an object can contain state. In fact, a function can do this in a weak sense, using a static local, but then a static local constant is present there for any call to this function executed in any context by any thread.

When an object acts as a function, the state is only a member of this object, and you can have other objects of the same class that have their own set of member variables.

At the heart of this concept is the completeness of boost :: bind (which was based on old STL binders).

The function has a fixed signature, but often you need more parameters than are actually passed in the signature to perform the action.

+3
source

Source: https://habr.com/ru/post/1335518/


All Articles