无论是将排序准则作为第二个template参数传入,或是采用缺省的排序准则less<>,通常你都会讲排序准则定义为型别的一部分。但是有时必须在执行期处理排序准则,或者你可能需要对同一种数据型别采用不同的排序准则。此时你就需要一个“用来表现排序准则”的特殊型别,使你能够在执行期间传递某个准则。以下范例程序说明了这种做法:
#include<iostream>
#include<set>
#include"print.h"
using namespace std;
//type for sorting criterion
template<class T>
class RuntimeCmp{
public:
enum cmp_mode{normal,reverse};
private:
cmp_mode mode;
public:
//constructor for sorting criterion default criterion uses value normal
RuntimeCmp(cmp_mode m = normal):mode(m){
}
//comparsion of elements
bool operator() (const T& t1,const T& t2)const{
return mode==normal ? t1<t2 : t2<t1;
}
//comparision of sorting criteria
bool operator == (const RuntimeCmp& rc){
return mode == rc.mode;
}
};
//type of a set that uses this sorting criterion
typedef set<int,RuntimeCmp<int> >IntSet;
//forward declaration
void fill(IntSet & set);
int main()
{
//creat,fill, and print set with normal element order uses default sorting criterion
IntSet coll1;
fill(coll1);
PRINT_ELEMENTS(coll1,"coll1: ");
//create sorting criterion with reverse element order
RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse);
//create,fill,and print set with reverse element order
IntSet coll2(reverse_order);
fill(coll2);
PRINT_ELEMENTS(coll2,"coll2: ");
//assign elements AND sorting criterion
coll1 = coll2;
coll1.insert(3);
PRINT_ELEMENTS(coll1,"coll1: ");
//just to make sure
if(coll1.value_comp() == coll2.value_comp()){
cout<<"coll1 and coll2 have different sorting criterion "<<endl;
}
return 0;
}
void fill(IntSet& set)
{
//fill insert elements in random order
set.insert(4);
set.insert(7);
set.insert(5);
set.insert(1);
set.insert(6);
set.insert(2);
set.insert(5);
}
#include<iostream>
using namespace std;
/* PRINT_ELEMENTS()
* -prints optional C-string optcstr followed by
* -all elements of the collection coll
* -separated by spaces
*/
template<class T>
inline void PRINT_ELEMENTS (const T& coll,const char * optcstr=" ")
{
typename T::const_iterator pos;
cout<<optcstr;
for(pos = coll.begin();pos != coll.end(); ++pos)
cout<<*pos<<ends;
cout<<endl;
}
在这个程序中,RuntimeCmp<>是一个简单的template,提供“执行期间面对任意型别定义一个排序准则”的泛化能力。其default构造函数采用默认值normal,按升序排序;你也可以将RuntimeCmp<>::reverse传递给构造函数,便能按降序排序。