函数模板:
template< typename T >
函数模板和普通函数都可以被调用时,优先考虑普通函数
如果函数模板可以产生一个更好的匹配,选择调用模板
代码示例:
template<typename T>
T Add(T left, T right)
{
return left + right;
}
int main()
{
cout << Add<int>(1, 2) << endl;
cout << Add<double>(1.0, 2.7) << endl;
system("pause");
return 0;
}
代码运行测试图:
类模板:
代码示例:
class-mod.h:
#pragma once
template<typename T>
class Seqlist
{
public:
Seqlist(size_t capacity = 3) :_array(new T[capacity]), _size(0), _capacity(capacity)
{
}
~Seqlist()
{
if (_array)
{
delete[] _array;
_size = 0;
_capacity = 0;
}
}
size_t Size()const
{
return _size;
}
size_t Capacity()const
{
return _capacity;
}
void PushBack(const T& data)
{
_array[_size++] = data;
}
void PopBack()
{
if (_size == 0)
{
return;
}
_size--;
}
T& operator[](size_t index)
{
return _array[index];
}
bool Empty()const
{
if (_size == 0)
{
return true;
}
return false;
}
void PrintSList()
{
for (int i = 0; i < _size; ++i)
{
cout << _array[i] << " ";
}
cout << endl;
}
private:
T* _array;
size_t _size;
size_t _capacity;
};
class-mod.cpp
#include "class-mod.h"
#include <iostream>
using namespace std;
int main()
{
Seqlist<int> d1;
d1.PushBack(1);
d1.PushBack(2);
d1.PushBack(3);
cout << d1.Capacity() << endl;
cout << d1.Size() << endl;
Seqlist<double>d2;
d2.PushBack(1.0);
d2.PushBack(2.0);
d2.PushBack(3.0);
cout << d2.Capacity() << endl;
cout << d2.Size() << endl;
d1.PrintSList();
d2.PrintSList();
cout << d1[1] << endl;
system("pause");
return 0;
}
代码运行测试图: