这是一个c++ 编程思想(2卷) 上的一个示例,试写了一下,算是对模板的一个练习
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <set>
#include <stdexcept>
using namespace std;
typedef vector<string> vecstr;
typedef set<string> setstr;
typedef ostream_iterator<string> outstr;
const bool TRUE = 1;
const bool FALSE = 0;
/*
void printElement(string str){
cout<<str<<endl;
}*/
//这个类与上述函数在下面的调用中作用相同
class printElement{
public:
void operator ()(string &str){
cout<<str<<endl;
}
};
template<class T,class V>
void AddElemtoContainter(T &s,const V &words) //默认的是vector,list等
{
s.push_back(words);
}
template<>
void AddElemtoContainter<setstr,string>(setstr &s,const string &words) //实例化set
{
s.insert(words);
}
template <class T>
bool populate_set_from_file(T &s,const char* file_no)
{
ifstream fin(file_no);
string words;
while(fin>>words){
if (fin.fail())
{
cout<<"Error in fstream."<<endl;
return FALSE;
}
AddElemtoContainter(s,words);
}
fin.close();
return TRUE;
}
template<class Containter_type,class Value_type>
void Container_Differences(const Containter_type &t1,const Containter_type &t2,Containter_type &t3)
{
Containter_type temp;
Containter_type::const_iterator pos_Con_fst,pos_find_at;
if(t1==t2) exit(0);
pos_Con_fst = t1.begin();
while (pos_Con_fst!=t1.end())
{
pos_find_at= find(t2.begin(),t2.end(),(*pos_Con_fst));
if(pos_find_at==t2.end())
AddElemtoContainter(temp,static_cast<string>(*pos_Con_fst));
pos_Con_fst++;
}
pos_Con_fst = t2.begin();
while (pos_Con_fst!=t2.end())
{
pos_find_at=find(t1.begin(),t1.end(),(*pos_Con_fst));
if(pos_find_at==t1.end())
AddElemtoContainter(temp,static_cast<string>(*pos_Con_fst));
pos_Con_fst++;
}
temp.swap(t3);
}
int main(int argc,char *argv[])
{
if(argc!=3)
{
cout << "compareFiles - copyright (c) Essam Ahmed 2000" << endl << endl;
cout << "This program compares the conents of two files and prints" << endl
<< "the differences between the files to the screen" << endl << endl;
cout << "Usage: compareFiles <file_name_1> <file_name_2>" << endl << endl;
return 1;
}
outstr os(cout,"/n");
setstr file1,file2,file3;
populate_set_from_file(file1,argv[1]);
cout<<"The element of the "<<argv[1]<<"is:"<<endl;
copy(file1.begin(),file1.end(),os);
populate_set_from_file(file2,argv[2]);
cout<<"The element of the "<<argv[2]<<"is:"<<endl;
copy(file2.begin(),file2.end(),outstr(cout,"/n"));
Container_Differences<setstr,string>(file1,file2,file3);
cout<<"The element of the difference is:"<<endl;
//在下式中printElement是唯一的,不能换成其他的名字。
// for_each(file3.begin(),file3.end(),printElement);
//在用类printElement时,要用printElement(),在这里先生成了一个临时对象,然后将其作为参数传递。
for_each(file3.begin(),file3.end(),printElement());
system("pause");
return 0;
}