Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functionality of void operator()()

Tags:

I am confused about the functionality of void operator()().

Could you tell me about that, for instance:

class background_task { public:      void operator()() const     {         do_something();         do_something_else();     } };  background_task f;  std::thread my_thread(f); 

Here, why we need operator()()? What is the meaning of the first and second ()? Actually, I know the operation of normal operator, but this operator is confusing.

like image 320
David Alex Avatar asked Aug 08 '12 03:08

David Alex


People also ask

What are void functions?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

How do you use void operator?

The JavaScript, the void operator is used to explicitly return undefined. Its a unary operator, meaning only one operand can be used with it. You can use it like shown below — standalone or with a parenthesis.

What is void function in C?

What is void in C programming? It means “no type”, “no value” or “no parameters”, depending on the context. We use it to indicate that: a function does not return value. a function does not accept parameters.

Why is my function void?

Void means completely empty. In JavaScript, the void is an operator, which is used when the function is not return anything. It means the void result is undefined. In Java, if we do not specify any return type then automatically that function or method becomes void.


2 Answers

You can overload the () operator to call your object as if it was a function:

class A { public:     void operator()(int x, int y) {         // Do something     } };  A x; x(5, 3); // at this point operator () gets called 

So the first parentheses are always empty: this is the name of the function: operator(), the second parentheses might have parameters (as in my example), but they don't have to (as in your example).

So to call this operator in your particular case you would do something like task().

like image 192
unkulunkulu Avatar answered Sep 19 '22 08:09

unkulunkulu


The first () is the name of the operator - it's the operator that is invoked when you use () on the object. The second () is for the parameters, of which there are none.

Here's an example of how you would use it:

background_task task; task();  // calls background_task::operator() 
like image 40
Mark Ransom Avatar answered Sep 19 '22 08:09

Mark Ransom