關(guān)鍵詞:模板參數(shù)類型、數(shù)組類模板實(shí)現(xiàn)
0. 預(yù)備知識(shí)
模板參數(shù)不僅僅是類型參數(shù),也可以是非類型參數(shù)如數(shù)值參數(shù)。
template
<typename T, int N>
void func()
{
T a[N]; // 使用模板參數(shù)定義局部數(shù)組
}
// func<double, 10>();

數(shù)值型模板參數(shù)的限制:
- 變量不能作為模板參數(shù)
- 浮點(diǎn)數(shù)不能作為模板參數(shù)
- 類對(duì)象不能作為模板參數(shù)
- ...
本質(zhì):模板參數(shù)是在編譯階段被處理的單元,因此,在編譯階段必須準(zhǔn)確無(wú)誤的唯一確定。
編程說(shuō)明:最高效的方法求1+2+3...+N的值
#include <iostream>
#include <string>
using namespace std;
template
<int N>
class Sum
{
public:
static const int VALUE = Sum<N-1>::VALUE + N;
};
template
< >
class Sum < 1 >
{
public:
static const int VALUE = 1;
};
int main()
{
cout << "1 + 2 + 3 + ... + 10 = " << Sum<10>::VALUE << endl;
cout << "1 + 2 + 3 + ... + 100 = " << Sum<100>::VALUE << endl;
return 0;
}
編程說(shuō)明:數(shù)組模板類
#ifndef _ARRAY_H_
#define _ARRAY_H_
template
< typename T, int N>
class Array
{
T m_array[N];
public:
int getLength();
bool set(int index, T value);
bool get(int index, T& value);
T& operator [] (int index);
T operator [] (int index) const;
virtual ~Array();
};
template
< typename T, int N>
int Array<T, N>::getLength()
{
return N;
}
template
< typename T, int N>
bool Array<T, N>::set(int index, T value)
{
bool ret = ( 0 <= index ) && ( index < N );
if(ret)
{
m_array[index] = value;
}
return ret;
}
template
< typename T, int N>
bool Array<T, N>::get(int index, T& value)
{
bool ret = ( 0 <= index ) && ( index < N );
if(ret)
{
value = m_array[index];
}
return ret;
}
template
< typename T, int N>
T& Array<T, N>::operator [] (int index)
{
return m_array[index];
}
template
< typename T, int N>
T Array<T, N>::operator [] (int index) const
{
return m_array[index];
}
template
< typename T, int N>
Array<T, N>::~Array()
{
}
#endif
輸出結(jié)果
a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16