3

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?

  • Please add more context, where you found that statement specifically. That will help others researching the same topic. – πάντα ῥεῖ Oct 06 '21 at 10:53
  • In general, if you see the `operator` keyword and don't recognize the overload or how to call it, check this page on [operators and overloading](https://en.cppreference.com/w/cpp/language/operators). – Useless Oct 06 '21 at 11:09
  • The name of the overloadable "function call" pseudo-operator function is `operator()`. The similar method in Python is called `__call__`. – molbdnilo Oct 06 '21 at 13:04

1 Answers1

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483