我正在寻找一种方法来实现我的代码,以便下面的泛型函数可以接受任何类型的变量,但是当它接受一个字符串时,它将使用下面的函数比较2个字符串,当它采用任何其他类型时变量,它将简单地使用正常的比较运算符。我试图使用函数重载来完成,如你所见:
#include <vector>
#include <iostream>
#include <string>
#include "binaryTreeInterface.h" // Overloading the functions here FYI
using namespace std;
template <typename E>
class binarySearchTree: binaryTreeInterface<E>{
public:
int LessThan<E>(E itm1, E itm2) {
if (itm1 < itm2) {return -1;}
else if (itm1 > itm2) {return 1;}
else if (itm1 == itm2) {return 0;}
}
int LessThan<string>(string s1, string s2) {
return strcmp(s1, s2);
}
void AddNode(E itm) {
/* ... */
if (LessThan(itm, v[i]) <= 0) {i = LeftChild(i);} // v[i] is a variable E
else if (LessThan(itm, v[i]) > 0) {i = RightChild(i);}
}
以下是我遇到的错误:
In file included from test_binarySearchTree.cpp:1:0:
binarySearchTree.h:26:9: error: expected ‘;’ at end of member declaration
int Compare<E>(E itm1, E itm2) {
^
binarySearchTree.h:26:16: error: expected unqualified-id before ‘<’ token
int Compare<E>(E itm1, E itm2) {
^
test_binarySearchTree.cpp:78:1: error: expected ‘}’ at end of input
}
^
In file included from test_binarySearchTree.cpp:1:0:
binarySearchTree.h:24:5: error: expected unqualified-id at end of input
}