数组类模板1
预备参数:
模板参数可以是数值型参数(非类型参数)
template <typename T, int N>
void func()
{
T a[N]; //使用模板参数定义局部数组
}
func<double, 10>();
数组型模板参数的限制:
(1)变量不能作为模板参数
(2)浮点数不能作为模板参数 //浮点数在内存中表示不准确
(3)类对象不能作为模板参数
本质:模板参数是在编译阶段被处理的单元,因此,在编译阶段必须准确无误的唯一确定。
有趣的面试题:
用你觉得最高效的方法求1+2+3+…+N的值!
实验编程:数值型模板参数
#include <iostream>
#include <string>
using namespace std;
template <typename T, int N>
void func()
{
T a[N]; //使用模板参数定义局部数组
for(int i = 0; i < N; i++)
{
a[i] = i;
}
for(int i = 0; i < N; i++)
{
cout << a[i] << endl;
}
}
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;
//int a = 10;
//func<double, a>(); //a是变量,变量不能作为模板参数
func<double, 10>();
}
实验编程:数组模板类