void operator()() const 的编程实践

void operator()() const

()操作符的名字, ()的操作将被调用,当对象前面用()时.

如下例:

class background_task
{
public:

    void operator()() const
    {
        do_something();
        do_something_else();
    }
};
/*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()

下面是void operator()() const 在c++标准线程库的编程实践

#include <QCoreApplication>
#include <iostream>
#include <thread> //用于管理线程的函数和类在<thread>中声明,而那些保护共享数据的函数和类在其它头文件中声明.

void do_something()
{//每个线程都必須具有的一个初始函数(initial fun)
    std::cout<<"do_something()\n";
}

void do_something_else()
{//每个线程都必須具有的一个初始函数(initial fun)
    std::cout<<"do_something_else()\n";
}

class background_task
{
public:
    void operator()() const{ //函数调用操作符的声明与定义
        do_something();
        do_something_else();
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    background_task f;
    std::thread my_thread(f);//my_thread(f),将一个带有函数调用操作符的类的实例传递给std::thread的构造函数,是一个经常使用的编程实践.
    my_thread.join();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u012915636/article/details/81978140