正如已经指出的那样,您不能强制比较拥有一个静态成员compare
。如果你的比较器没有实现它,你只会得到一个编译器错误。
如果您像这样实现,则将其声明为模板模板参数AVLTree
会更优雅:Comparer
template <typename K>
class DefaultComparer
{
public:
static bool compare(K k1, K k2)
{ return k1 == k2; }
};
template <typename K>
class MyComparer : public DefaultComparer<K>
{
public:
static bool compare(K k1, K k2)
{ return k1 <= k2; }
};
template <typename K>
class InvalidComparer
{
public:
static bool bar(K k1, K k2)
{ return k1 != k2; }
// Doesn't implement compare()
};
// Compare is a template template paramenter with default template argument
// DefaultComparer
template <typename K, template <typename K> class Comparer = DefaultComparer>
class AVLTree
{
K k1, k2;
public:
AVLTree() : k1(0), k2(0) { } // ctor
bool foo();
};
// Definiton of AVLTree::foo()
template <typename K, template <typename K> class Comparer>
bool AVLTree<K, Comparer>::foo()
{
return Comparer<K>::compare(k1, k2);
}
int main(int argc, char *argv[])
{
// Without template template parameters you
// would have to use AVLTree<int, DefaultComparer<int> >
AVLTree<int> avltree;
// instead of AVLTree<int, MyCompare<int> >
AVLTree<int, MyComparer> avltree2;
// Calling foo() will generate a compile error.
// But if you never call avltree3.foo() this will compile!
AVLTree<int, InvalidComparer> avltree3;
avltree.foo(); // calls DefaultComparer::compare
avltree2.foo(); // calls MyComparer::compare
avltree3.foo(); // fails to compile
}
见:http ://codepad.org/OLhIPjed