2
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++?

4

3 回答 3

8

There is no pre-existing function in C++ that performs comparison on ints. 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:

  1. Use std::less,

    this->lessThan = std::less<Key>();
    
  2. Use a lambda:

    this->lessThan = [](const Key& k1, const Key& k2){ return k1 < k2; };
    
  3. 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().

于 2016-06-22T20:44:31.747 回答
4
template<class Key, class Value>
AVLTree<Key,Value>::AVLTree()
{
    this->lessThan = std::less<Key>();
}

http://en.cppreference.com/w/cpp/utility/functional/less

于 2016-06-22T20:44:56.503 回答
1

You need to implement Template Specialization for built-in types like int, double, char, etc. It's impossible to query for the relational operators on built-in types, which causes your code to fail.

于 2016-06-22T20:43:05.743 回答