简体   繁体   中英

Can a class member function be invoked without an object?

I was learning the history about Lambda's in C++ and saw the following code (which is not lambda) but I am surprised how it Works

struct Printer{
void operator() (int x) const{
    std::cout << x << '\n';
 }
};

 int main(){
   std::vector <int> vint;
   //doing it the C++ 03 way
    vint.push_back(1);
    vint.push_back(7);

 std::for_each(vint.begin(),vint.end(), Printer());

}

How is the Printer() call in the for_each function working?

Printer() is an instance of the Printer class. It will result in a temporary object of type Printer which is passed to std::for_each .

This is the object on which operator() is called by std::for_each internally.

Without an object of type Printer , it is not possible to call the operator() member function.

Can a class member function be invoked without an object?

If it is a static member function then yes, it can be invoked without instance of the class.

If it is a non-static member function, then no, it can not be invoked without instance of the class. The example operator() function is a non-static member function, so it cannot be called without an instance.

How is the Printer() call in the for_each function working?

Printer() is syntax for value initialisation of a temporary object. The temporary instance of Printer class is passed as an argument into std::for_each .

Here Printer() constructs an object that is used by for_each . It is not a function that is called. The function that is called is Printer() 's operator()()

It works because for_each is a template function that applies () to its third argument without caring what the third argument really is:

for_each is defined something like this,

template <typename Iter, typename sth> sth for_each(Iter start, Iter end, sth f){
  
  while(start != end) f(*start ++);
  return f;

 }

If the std::for_each is confusing (you provide a callable which is called by the algorithm), replace it with

 for (auto i: vint) Printer()(i);

which does the same thing: make a temporary object and call operator() with the needed parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM