Function call operator [duplicate]
Asked Answered
A

2

7

Possible Duplicates:
C++ Functors - and their uses.
Why override operator() ?

I've seen the use of operator() on STL containers but what is it and when do you use it?

Adoptive answered 14/1, 2011 at 9:1 Comment(4)
@Troubadour: quite probably, but someone who does not know what is the use of operator() is unlikely to know what is a functor and would not look for that question.Parboil
@Gorpik: Yes, but I think even the most rudimentary searching would reveal the relationship between operator() and functors.Pleach
On the other hand: https://mcmap.net/q/23223/-why-override-operatorParboil
@Gorpik: spot on, however typing operator() in the search box strips the (), very annoying "sanitizing" I guess :/Domenic
A
10

That operator turns your object into functor. Here is nice example of how it is done.

Next example demonstrates how to implement a class to use it 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;
}
Apodictic answered 14/1, 2011 at 9:5 Comment(2)
That's a way over complex example to be good. +1 if you add a nice example to your answer, rather than link it.Breaker
@Martin Is above good enough? The same could have been archived using a function.Antemundane
R
4

It makes the object "callable" like a function. Unlike a function though, an object can hold state. Actually a function can do this in a weak sense, using a static local, but then that static local is permanently there for any call to that function made in any context by any thread.

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

The entirety of boost::bind (which was based on the old STL binders) is based on this concept.

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

Returnable answered 14/1, 2011 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.