David Alex David Alex - 11 days ago 8
C++ Question

Functionality of void operator()()

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.

Answer

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