版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88624767
一 第一个函数模板的例子
1 代码
#include <iostream>
using namespace std;
template <class T> T GetMax(T a, T b) {
T result;
result = (a > b) ? a : b;
return (result);
}
int main() {
int i = 5, j = 6, k;
long l = 10, m = 5, n;
// 因为i和j都是int类型,编译器会自动假设我们想要的函数按照int进行调用。
k = GetMax(i, j);
//k = GetMax<int>(i, j);
n = GetMax(l, m);
//n = GetMax<long>(l, m);
cout << k << endl;
cout << n << endl;
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
6
10
二 类模板
1 代码
#include <iostream>
using namespace std;
template <class Type>
class compare
{
public:
compare(Type a, Type b)
{
x = a;
y = b;
}
Type max()
{
return (x > y) ? x : y;
}
Type min()
{
return (x < y) ? x : y;
}
private:
Type x;
Type y;
};
int main(void)
{
compare<int> C1(3, 5);
cout << "max:" << C1.max() << endl;
cout << "min:" << C1.min() << endl;
compare<float> C2(3.5, 3.6);
cout << "max:" << C2.max() << endl;
cout << "min:" << C2.min() << endl;
compare<char> C3('a', 'd');
cout << "max:" << C3.max() << endl;
cout << "min:" << C3.min() << endl;
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
max:5
min:3
max:3.6
min:3.5
max:d
min:a
三 模板的参数值
1 代码
#include <iostream>
using namespace std;
// 模板参数包含其他不是代表一个类型的参数,例如代表一个常数,这些通常是基本数据类型
template <class T, int N>
class array {
T memblock[N];
public:
void setmember(int x, T value);
T getmember(int x);
};
template <class T, int N>
void array<T, N>::setmember(int x, T value) {
memblock[x] = value;
}
template <class T, int N>
T array<T, N>::getmember(int x) {
return memblock[x];
}
int main() {
array <int, 5> myints;
array <float, 5> myfloats;
myints.setmember(0, 100);
myfloats.setmember(3, 3.1416);
cout << myints.getmember(0) << '\n';
cout << myfloats.getmember(3) << '\n';
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
100
3.1416
四 说明
模板的功能对文件工程有一定的限制:函数或模板的实现必须与原型声明在同一个文件中,也就是说,我们不能再将接口存储在单独的头文件中,而必须将接口和实现放在使用模板的同一个文件中。