How to properly overload functions

时间:2017-11-13 06:18:56

标签: c++ binary-search-tree overloading

Hi I was just wondering how I would go about properly overloading functions in a Binary Search Tree. Heres the Code I have:

int LessThan(E itm1, E itm2) {
  if (itm1 < itm2) {return -1;}
  else if (itm1 > itm2) {return 1;}
  else if (itm1 == itm2) {return 0;}
}

int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
  return this->compare(s1, s2);
}

Unfortunately I'm getting the following errors:

binarySearchTree.h:33:9: error: ‘int binarySearchTree<E>::LessThan(std::__cxx11::string, std::__cxx11::string) [with E = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]’ cannot be overloaded
 int LessThan(string s1, string s2) { // Incase it is a string, we need to define <= and >= differently
     ^
binarySearchTree.h:27:9: error: with ‘int binarySearchTree<E>::LessThan(E, E) [with E = std::__cxx11::basic_string<char>]’
 int LessThan(E itm1, E itm2) {
     ^

1 个答案:

答案 0 :(得分:2)

Overloading isn't the answer to your problem. You are trying to have a specific behavior when your template is instantiated with a std::string. The proper technique is explicit specialization. Add the following under your template definition, like so:

template<>
int binarySearchTree<std::string>::LessThan(std::string s1, std::string s2) {
  return this->compare(s1, s2);
}