1.2.6 模板的局限性

143 阅读1分钟

模板并不是万能的,有些特定数据类型,需要用具体化方式做特殊实现。

#include <iostream>

using namespace std;

class Person
{
public:
	Person(int age, string name)
	{
		this->age = age;
		this->name = name;
	}
	int age;
	string name;
};

template<class T>
bool my_compare(T& a, T& b)
{
	if (a == b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// 将模板函数具体化
template<> bool my_compare(Person& a, Person& b)
{
	if (a.name == b.name && a.age == b.age)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void test()
{
	int a = 10;
	int b = 20;
	bool ret = my_compare(a, b);
	if (ret)
	{
		cout << "a == b" << endl;
	}
	else
	{
		cout << "a != b" << endl;
	}
}

void test2()
{
	Person a(20, "Li");
	Person b(20, "Li");
	bool ret = my_compare(a, b);
	if (ret)
	{
		cout << "a == b" << endl;
	}
	else
	{
		cout << "a != b" << endl;
	}
}

int main()
{
	test();
	test2();

	system("pause");
	return 0;
}

总结:

  • 利用具体化模板,可以解决自定义类型的通用化
  • 学习模板是为了在STL能够运用系统提供的模板