void operator()()的功能

Dav*_*lex 20 c++

我对它的功能感到困惑void operator()().

你能告诉我这个,例如:

class background_task
{
public:

    void operator()() const
    {
        do_something();
        do_something_else();
    }
};

background_task f;

std::thread my_thread(f);
Run Code Online (Sandbox Code Playgroud)

在这里,为什么我们需要operator()()?第一个和第二个是什么意思()?实际上,我知道普通算子的操作,但这个操作符令人困惑.

unk*_*ulu 26

您可以重载()操作符来调用您的对象,就好像它是一个函数:

class A {
public:
    void operator()(int x, int y) {
        // Do something
    }
};

A x;
x(5, 3); // at this point operator () gets called
Run Code Online (Sandbox Code Playgroud)

所以第一个括号总是空的:这是函数的名称:operator()第二个括号可能有参数(如我的例子中所示),但它们没有(如在你的例子中).

因此,在您的特定情况下调用此运算符,您将执行类似的操作task().


Mar*_*som 21

第一个()是运算符的名称 - 它是()在对象上使用时调用的运算符.第二个()是参数,其中没有参数.

以下是如何使用它的示例:

background_task task;
task();  // calls background_task::operator()
Run Code Online (Sandbox Code Playgroud)


Dav*_*ave 7

第一部分operator()是声明在将类的实例作为函数调用时调用的函数的方法.第二对括号将包含实际参数.

使用返回值和参数,这可能会更有意义:

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) );
Run Code Online (Sandbox Code Playgroud)

在这个上下文中,std::thread将在内部调用内部调用f(),即内部的任何operator()内容都是在该线程内部完成的.