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.
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.
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 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.
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.
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()
.
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()
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