一、为什么需要有模板?
以实现比较大小函数功能为例子,我们如下展开代码:
- 为同一种数据结构或者算法定义适用于不同类型的版本。–代码冗余
#include <iostream>
using namespace std;
int max_int(int x, int y)
{
return x > y ? x : y;
}
double max_double(double x, double y)
{
return x > y ? x : y;
}
string max_string(string x, string y)
{
return x > y ? x : y;
}
int main(void)
{
cout << max_int(123, 456) << endl;
cout << max_double(1.23, 4.56) << endl;
cout << max_string("hello", "world") << endl;
return 0;
}
- 借助参数宏拜托类型的约束,同时也丧失了类型的安全。–潜在风险
#include <iostream>
using namespace std;
#define max(x, y) ((x) > (y) ? (x) : (y))
int main(void)
{
cout << max(123, 456) << endl;
cout << max(1.23, 4.56) << endl;
cout << max("hello", "world") << endl;
return 0;
}
- 让预处理器自动的生成不同类型的函数版本。 –不易调试
#include <iostream>
using namespace std;
#define MAX(T) \
T max_##T(T x, T y) \
{ \
return x > y ? x : y; \
}
MAX(int)
MAX(double)
MAX(string)
#define max(T) max_##T
int main(void)
{
cout << max(int)(123, 456) << endl;
cout << max(double)(1.23, 4.56) << endl;
cout << max(string)("hello", "world") << endl;
return 0;
}
- 编写带有参数化类型的通用版本,让编译器自动的生成针对不同类型的具体版本。 –模板!
#include <iostream>
using namespace std;
template <typename T>
T max(T x, T y)
{
return x > y ? x : y;
}
int main(void)
{
cout << ::max<int>(123, 456) << endl;
cout << ::max<double>(1.23, 4.56) << endl;
cout << ::max<string>("hello", "world") << endl;
return 0;
}