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?
A function call is a kind of postfix-expression , formed by an expression that evaluates to a function or callable object followed by the function-call operator, () . An object can declare an operator () function, which provides function call semantics for the object.
To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with. class className { ... .. ... public returnType operator symbol (arguments) { ... .. ... } ... .. ... };
Python supports both function and operator overloading. In function overloading, we can use the same name for many Python functions but with the different number or types of parameters. With operator overloading, we are able to change the meaning of a Python operator within the scope of a class.
Python does not allow to create own operators, a design decision which was made for a good reason and you should accept it instead of seeing this as a problem and inventing ways around it. It is not a good idea to fight against the language you are writing the code in.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With