What is this function object?

W

webinfinite

Could anyone explain this snippet for me?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class PrintInt {
public:
void operator() (int elem) const {
cout << elem << ' ';
}
};

int main() {
vector<int> coll;
for (int i = 1; i <=9; ++i)
coll.push_back(i);

for_each (coll.begin(), coll.end(), PrintInt()); // I don't
understand here
}

for_each needs a function object, so if we are doing: PrintInt p, then
we call for_each(coll.begin(), coll.end(), p()); I will understand,
but what is this "PrintInt()" here? Is it a default constructor? Or
just a call to overloaded operator ()?

Thank you for your response.
 
Z

zhangyw80

Here,PrintInt(),is a function object yet.
It runs constructor first (doing nothing here) , and runs operator()
later.









- -

accurately, opeartor() is called inside for_each, not immediately
after default constructor
 
P

Pete Becker

Could anyone explain this snippet for me?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class PrintInt {
public:
void operator() (int elem) const {
cout << elem << ' ';
}
};

int main() {
vector<int> coll;
for (int i = 1; i <=9; ++i)
coll.push_back(i);

for_each (coll.begin(), coll.end(), PrintInt()); // I don't
understand here
}

for_each needs a function object, so if we are doing: PrintInt p, then
we call for_each(coll.begin(), coll.end(), p()); I will understand,

But that call would be wrong. The algorithm needs the object, not the
result of calling its operator(). So the correct call is
for_each(coll.begin(), coll.end(), p);
but what is this "PrintInt()" here? Is it a default constructor? Or
just a call to overloaded operator ()?

Yes, it's the default contructor. It creates an unnamed temporary
object, and for_each gets a copy of that object. for_each calls the
copy's operator() as needed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top