c++标准程序库中:
The following is a complete example. This is the function object version of a previous example (see page 119) that did the same with an ordinary function:
// stl/foreach2.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//simple function object that prints the passed argument
class PrintInt {
public:
void operator() (int elem) const {
cout << elem << ' ';
}
};
int main()
{
vector<int> coll;
//insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
//print all elements
for_each (coll.begin(), coll.end(), //range
PrintInt()); //operation
cout << endl;
}
The class PrintInt defines objects for which you can call operator () with an int argument. The expression
PrintInt()
in the statement
for_each (coll.begin(), coll.end(),
PrintInt());
creates a temporary object of this class, which is passed to the for_each() algorithm as an argument. The for_each() algorithm is written like this:
namespace std {
template <class Iterator, class Operation>
Operation for_each (Iterator act, Iterator end, Operation op)
{
while (act != end) { //as long as not reached the end
op (*act); // - call op() for actual element
act++; // - move iterator to the next element
}
return op; }
}
}
for_each() uses the temporary function object op to call op(*act) for each element act. If the third parameter is an ordinary function, it simply calls it with *act as an argument. If the third parameter is a function object, it calls operator () for the function object op with *act as an argument. Thus, in this example program for_each() calls:
PrintInt::operator()(*act)
You may be wondering what all this is good for. You might even think that function objects look strange, nasty, or nonsensical. It is true that they do complicate code. However, function objects are more than functions, and they have some advantages: