60_数组类模板

关键词:模板参数类型、数组类模板实现

0. 预备知识

模板参数不仅仅是类型参数,也可以是非类型参数数值参数

template
<typename T, int N>
void func()
{
    T a[N];     // 使用模板参数定义局部数组
}
// func<double, 10>();

数值型模板参数的限制

  • 变量不能作为模板参数
  • 浮点数不能作为模板参数
  • 类对象不能作为模板参数
  • ...

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

编程说明:最高效的方法求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;
}

编程说明:数组模板类

#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

输出结果

a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容