use of operator() in a class or struct

Hi All,

in some of the code that i am reusing. i was surprise to see
operator()
operator used in a struct.

dose any one knows what this operator is and how it works?
searched around the internet but could not found any answer


1
2
3
4
5
6
7
struct EventSetter
{
	void operator()()
	{
		SetEvent(BackgroundTask, event_writer);
	}
};

Last edited on
It's the function call operator. Calling it will look like a function call
1
2
EventSetter es;
es(); // this calls operator() 
closed account (zb0S216C)
I'm not too sure of the name, but the operator can be used for anything; functional notation, accessing something within an array, return a piece of data, et cetera. There's no defined suggestion as to what each overloaded operator should do. For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct Structure
{
    // To return something:
    int operator () ()
    {
        int MyInt(0);
        
        // Do something with "MyInt"...

        return(MyInt);
    }

    // To access an array:
    int MyArray[3];
    int &operator () (int Index = 0) const
    {
        return(this->MyArray[Index]);
    }
 
    // As a function:
    void operator () ()
    {
        // Do something a function would do...
    }
};

Wazzak
The most typical of uses for this operator is functors and the STL, I would say.
The operator() is wildly used in STL, mostly as a function object. It is also used in expression template in the same way, as function object

e.g.
1
2
3
4
5
6
7
template<class T, class Op>
ResultObj< ResultObj< T, T , Op > , OtherObj< T, T , Op >,OperationObj< typename ResultObj< T, T , Op >::value_type> >

operator + (const ResultObj< T, T , Op >& a, const OtherObj< T, T , Op >& b)
{
	return ResultObj< ResultObj< T, T , Op > , OtherObj< T, T , Op >,OperationObj< typename ResultObj< T, T , Op >::value_type> > (a,b, OperationObj< typename ResultObj< T, T , Op >::value_type>() ) ;
}
Topic archived. No new replies allowed.