template<class Key, class Value>
AVLTree<Key,Value>::AVLTree(){
this->lessThan = Key::operator<;
}
This code is supposed to make the std::function<bool(Key, Key)> lessThan
field equal to the key's < operator by default. However, when I try this with AVLTree<int,int>
, I get:
error: ‘operator<’ is not a member of ‘int’
Am I formatting this wrong, or is this just impossible in C++?
There is no pre-existing function in C++ that performs comparison on int
s. Furthermore, even if Key
is a class type, you can't know whether it has a member or non-member operator<
.
Here are some alternatives:
Use std::less
,
this->lessThan = std::less<Key>();
Use a lambda:
this->lessThan = [](const Key& k1, const Key& k2){ return k1 < k2; };
If you design AVLTree
like the standard library containers, the type of the comparison object should be a type template parameter Comp
defaulting to std::less<Key>
, with an instance passed in the constructor, defaulting to Comp()
.