I was aksed to write a program for tutoring the usage of for_each() and ran into the question
os = src.os; // this does not compile
Following is the code (read the comments and try to help me answer the qeustion):
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
void printFunction(int i)
{
cout<<i<<" ";
}
template<typename T>
struct printFunctor : public unary_function<T, void>
{
printFunctor(ostream& os_=cout) : os(os_), count(0)
{
}
printFunctor<T>& operator= (const printFunctor<T>& src)
{
if(this!=&src)
{
// copyfmt() does the job, but it is not an
// exact copy of the original stream (in src).
//
// Do we have something which is more like
//
// os = src.os;
os.copyfmt(src.os);
count=src.count;
}
return *this;
}
void operator()(const T& x)
{
os<<x<<" ";
++count;
}
ostream& os;
int count;
};
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(4);
v.push_back(8);
v.push_back(16);
for_each(v.begin(), v.end(), printFunction); // &printFunction is ok as well
cout<<endl;
ofstream ofs("out.txt");
if(!ofs)
{
cout<<"cannot open file.\n";
exit(1);
}
/** If we haven't overridden the assignment op, we can use the following syntax:
printFunctor<int> P = for_each(v.begin(), v.end(), printFunctor<int>(cout));
*/
printFunctor<int> P;
printFunctor<int> Q(ofs);
P = for_each(v.begin(), v.end(), P);
cout<<endl<<P.count<<endl;
Q = for_each(v.begin(), v.end(), Q);
ofs<<endl<<Q.count<<endl;
ofs.close();
return 0;
}
[此贴子已经被作者于2007-8-30 6:56:19编辑过]