Search code examples
c++templatesc++11operatorsfunction-object

How do I assign an std::function to an operator in C++?


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


Solution

  • 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().