第60课.数组类模板

1.数组模板

模板参数可以是数值型参数(非类型参数)

template < typename T, int N >
void func()
{
T a[N]; // 使用模板参数定义局部数组
}
数值类型模板参数的限制
a.变量不能作为模板参数
b.浮点数不能作为模板参数
c.类对象不能作为模板参数
d....

本质:模板参数是在编译阶段被处理的单元,因此在编译阶段必须准确无误的唯一确定

编程:用你觉得最高效的方法求1+2+3+4+...+N的值

eg:

include

include

using namespace std;

template < typename T, int N >
void func()
{
T a[N] = {0};

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::VALUE + N;
};

template < >
class Sum < 1 > // 完全特化
{
public:
static const int VALUE = 1;
};

int main()
{
cout << "1 + 2 + 3 + 4 + ... + 10 = " << Sum<10>::VALUE << endl;
cout << "1 + 2 + 3 + 4 + ... + 100 = " << Sum<100>::VALUE << endl;

return 0;
}

2.数组类模板

eg:

ifndef ARRAY_H

define ARRAY_H

template < typename T, int N >
class Array
{
T m_array[N];
public:
int length();
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>::length()
{
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 >
virtual Array<T, N>::~Array()
{

}

endif /* ARRAY_H */

posted @ 2019-12-10 15:53  人民广场的二道贩子  阅读(253)  评论(0)    收藏  举报