从 C 向 C++ 进阶系列导航
1. 数值型模版参数
模板参数除了有数据类型外,还有数值类型。声明方法如下:
template <Type N>
...
其中,Type 为显式的数据类型,一般为 int。使用数值型模板参数有以下限制:
变量不能作为模板参数。
浮点数不能作为模板参数。
类对象不能作为模板参数。
数值型模板参数本质是模板参数是在编译阶段被处理的单元,因此在编译阶段必须准确无误的唯一确定。
- 实验:
使用数值型模板参数实现累加和。
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; // 1+2+3+...+10 = 55
cout << "1+2+3+...+100 = " << Sum<100>::VALUE << endl; // 1+2+3+...+100 = 5050
return 0;
}
2. 数组类模版
我们可以利用数值型模板参数来实现一个简单的数组类模板。
- 实验:
/* array.h */
#ifndef _ARRAY_H_
#define _ARRAY_H_
template <typename T, int N>
class Array
{
private:
T mNums[N];
public:
Array(int num = 0);
virtual ~Array();
int length();
void print();
T& operator [] (int num);
T& operator = (T& ref);
};
template <typename T, int N>
Array<T, N>::Array(int num)
{
for(int i = 0; i < N; i++)
{
mNums[i] = num;
}
}
template <typename T, int N>
Array<T, N>::~Array()
{
}
template <typename T, int N>
T& Array<T, N>::operator = (T& ref)
{
if(ref == *this)
{
return *this;
}
for(int i = 0; i < N; i++)
{
this->mNums[i] = ref.mNums[i];
}
return *this;
}
template <typename T, int N>
T& Array<T, N>::operator [] (int index)
{
return mNums[index];
}
template <typename T, int N>
int Array<T, N>::length()
{
return N;
}
template <typename T, int N>
void Array<T, N>::print()
{
cout << "mNums = {";
for(int i = 0; i < N - 1; i++)
{
cout << mNums[i] << ", ";
}
cout << mNums[N-1] << "}" << endl;
}
#endif
/* main.c */
#include <iostream>
#include <cstring>
using namespace std;
#include "array.h"
int main()
{
Array<int, 10> arr_A(0);
arr_A.print(); // mNums = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
cout << "arr_A.length() = " \
<< arr_A.length() << endl; // arr_A.length() = 10
for(int i = 0; i < arr_A.length(); i++)
{
arr_A[i] = i;
}
arr_A.print(); // mNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Array<int, 10> arr_B = arr_A;
arr_B.print(); // mNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
return 0;
}