模板並不是萬能的的。有其侷限性。 舉個例子,將a付給b,如果a,b是數組,那麼模板都會報錯。 直接用模板比較兩個類的大小也是行不通的。
就拿比較大小來舉例子吧
正常情況下
template<class T>
bool compare(T& a, T& b) {
if (a > b) {
reture true}
else {
reture false;
}
}
int main() {
int a = 20; int b = 30;
bool jud = compare(a, b);
if (jud == true) {
cout << "a大" << endl;
}
if (jud == false) {
cout << "b大" << endl;
}
}
如果比較的類型是個類
class test {
public :
int number;
int age;
string rank;
};
bool compare(T& a, T& b) {
if (a > b) {
return true;
}
else {
return false;
}
}
int main() {
test a = { 10 };
test b = { 20 };
bool jud = compare(a, b);
if (jud == true) {
cout << "a大" << endl;
}
if (jud == false) {
cout << "b大" << endl;
}
}
報錯了,那該怎麼辦呢?
-
1.運算符重載(比較複雜所以這裏不太推薦)
略
-
2.具體化模板
class test {
public:
int number;
int age;
string rank;
};
template<class T>
bool compare(T& a, T& b) {
if (a > b) {
return true;
}
else {
return false;
}
}
template<> bool compare(test& a, test& b) {
if (a.age == b.age && a.number == b.number && a.rank == b.rank) {
return true;
}
else {
return false;
}
}
int main() {
test a = { 10,20 ,"一等" };
test b = { 20,20,"二等" };
bool jud = compare(a, b);
if (jud) {
cout << "a大" << endl;
}
if (!jud ) {
cout << "b大" << endl;
}
}
核心就是這一塊具體化compare模板
template<> bool compare(test& a, test& b) {
if (a.age == b.age && a.number == b.number && a.rank == b.rank) {
return true;
}
else {
return false;
}
}