Functionality of void operator()()

前端 未结 4 608
一生所求
一生所求 2021-02-01 05:11

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

Could you tell me about that, for instance:

class background_task
{
public:

            


        
4条回答
  •  执笔经年
    2021-02-01 05:20

    The first part operator() is the way to declare the function that is called when an instance of the class is invoked as a function. The second pair of parentheses would contain the actual arguments.

    With a return value and arguments this might make a bit more sense:

    class Adder{
    public:
    int operator()(int a, int b){
        //operator() -- this is the "name" of the operator
        //         in this case, it takes two integer arguments.
        return a+b;
    }
    };
    Adder a;
    assert( 5==a(2,3) );
    

    In this context, the std::thread will internally invoke f() inside the thread, i.e. whatever is inside the body of operator() is what gets done inside that thread.

提交回复
热议问题