Templates and container classes
首先我们看下面的类
class IntArray
{
private:
int m_nLength;
int *m_pnData;
public:
IntArray()
{
m_nLength = 0;
m_pnData = 0;
}
IntArray(int nLength)
{
m_pnData = new int[nLength];
m_nLength = nLength;
}
~IntArray()
{
delete[] m_pnData;
}
void Erase()
{
delete[] m_pnData;
// We need to make sure we set m_pnData to 0 here, otherwise it will
// be left pointing at deallocated memory!
m_pnData = 0;
m_nLength = 0;
}
int& operator[](int nIndex)
{
assert(nIndex >= 0 && nIndex < m_nLength);
return m_pnData[nIndex];
}
int GetLength() { return m_nLength; }
};
使用这个类,我们可以方便的创建整数数组,但是如果我们想要创建double数组,传统的做法需要创建一个全新的类。使用template class则是一个简单高效的新方法。
template <typename T>
class Array
{
private:
int m_nLength;
T *m_ptData;
public:
Array()
{
m_nLength = 0;
m_ptData = 0;
}
Array(int nLength)
{
m_ptData= new T[nLength];
m_nLength = nLength;
}
~Array()
{
delete[] m_ptData;
}
void Erase()
{
delete[] m_ptData;
// We need to make sure we set m_pnData to 0 here, otherwise it will
// be left pointing at deallocated memory!
m_ptData= 0;
m_nLength = 0;
}
T& operator[](int nIndex)
{
assert(nIndex >= 0 && nIndex < m_nLength);
return m_ptData[nIndex];
}
// The length of the array is always an integer
// It does not depend on the data type of the array
int GetLength(); // templated GetLength() function defined below
};
template <typename T>
int Array<T>::GetLength() { return m_nLength; }
值得注意的是我们在类的外面定义了GetLength()成员函数。这就需要这个函数有自己的template declaration。 而且template array class是Array<T>而不是Array。
下面是个使用上述template class的例子
int main()
{
Array<int> anArray(12);
Array<double> adArray(12);
for (int nCount = 0; nCount < 12; nCount++)
{
anArray[nCount] = nCount;
adArray[nCount] = nCount + 0.5;
}
for (int nCount = 11; nCount >= 0; nCount----;)
std::cout << anArray[nCount] << "\t" << adArray[nCount] << std::endl;
return 0;
}
和template函数类似,template类也是在调用的时候由编译器实例化。