What is the ()() operator in C++?

Viewed 126

What void operator()() does? Found this while trying to rewrite a C++ program in python but can't even understand the functionality of this method. Its not called from anywhere in code but it is called anyway by a program and cant really understand what is this about? When is something like this called by program itself?

class MoistureSensor {
    const std::chrono::seconds sleepTime;
    std::mutex& mtx;
    std::set<WaterDevice*> devices;

    const int min = 0;
    const int max = 10;
    const int threshold = 3;

public:
    MoistureSensor(const std::chrono::seconds sleepTime, std::mutex& mtx)
        : sleepTime{ sleepTime }
        , mtx{ mtx }
    {
    }

    void subscribe(WaterDevice& device) {
        devices.insert(&device);
    }

    void operator()(){
        for (;;) {
            std::cout << "this\n";
            std::unique_lock<std::mutex> lock(mtx);

            if (isAirTooDry())
                for (auto p : devices)
                    p->sprinkleWater();
            if (isSoilTooDry())
                for (auto p : devices)
                    p->pourWater();

            lock.unlock();
            std::this_thread::sleep_for(sleepTime);
        }
    }
    void foo();
private:
    bool isAirTooDry();
    bool isSoilTooDry();
    int getAirMoisture();
    int getSoilMoisture();
};

Is there an equivalent of something like this in Python?

1 Answers

It's a functor that doesn't take any arguments and has no return value. Think of the first () as being the name of the operator, with the second () denoting the parameters.

For example, if Foo has such an operator, and foo is an instance of Foo, then

foo();

will call void operator()().

It's useful if you want to separate the construction of foo from its invocation. In many ways this was the precursor to lambda functions in C++, especially given that you can declare and define a type completely within the scope of a function.

Related