模板的侷限性

模板並不是萬能的的。有其侷限性。 舉個例子,將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;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章