以前看过《C++标准程序库》,所以乘此机会小复习下。
什么是伪函数?
伪函数是范型编程强大威力和纯粹抽象概念的又一个例证。你可以这么说,任何东西,只要其行为像函数,它就是个函数。因此,如果你定义了一个对象,行为向函数,它就可以被当作函数来用。好,那么什么才算是具备函数行为?所谓函数行为,是指可以”使用小括号传递参数,来调用某个东西”。例如:
function(arg1,arg2); //a function call
如果你指望对象也可以如此这般,就必须让他们也有可能被“调用”——通过小括号的运用和参数的传递。你只需要定义operator(),并给予合适的参数型别:
class X{
public:
//define '' function call '' operator
return-value operator() ( arguments) const;
};
现在,你可以把这个类别的对象当作函数来调用了:
X fo;
……
fo(arg1,arg2); // call operator( ) for function object fo
上述调用等同于:
fo.operator() (arg1,arg2);
下面使用函数对象实现二叉查找树的示例
template <typename Object,typename Comparator=less<Object> >
class BinarySearchTree
{
public:
// Same method , with Object replacing Comparable
private:
BinaryNode * root;
Comparator isLessThan;
//Same methods, with Object replacing Comparable
/**
* Internal methods to test if an item is in a subtree.
* x is item to search for.
* t is the node that roots the subtree.
* /
bool contains(const object & x, BinaryNode * t) const
{
if( t == NULL)
return false;
else if ( isLessThan(x, t->element)
return contains(x,t->left);
else if ( isLessThan(t->element ,x ) )
return contains(x,t->right);
else
return truel //Match
}
};