dimanche 2 juin 2019

Why overload the () operator (callable operator) in a C++ class or struct when you could use a constructor?

Why would you overload the () operator in a C++ class or struct in C++11 or higher? As far as I can tell, these operators are overloaded when you want to pass objects like classes or structs into a std::thread and kick off a new thread with a package of data to go along with it, through a callable type. But other than that, why else would you overload the () operator? Couldn't you simply do the same things in the constructor for a class or struct?

Why use

  struct MyCallableStruct{
    void operator() () {
        dosomething();
    }
  }

when you could do

  struct MyCallableStruct{
      MyCallableStruct() { dosomething(); }
  }

Aucun commentaire:

Enregistrer un commentaire