模板的局限性

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