數組類模板


  • 模板參數可以是數值型參數(非類型參數)
template <typename T,int N>
void func()
{
    //使用模板參數定義局部數組
    T a[n];
}
  • 數值型模板參數的限制
  1. 變量不能作為模板參數
  2. 浮點數不能作為模板參數
  3. 類對象不能作為模板參數
  4. 本質:模板參數是在編譯階段被處理的單元,因此,在編譯階段必須准確無誤的唯一確認。
  • 有趣的題目:使用最高效的方法求1+2+3+4+...+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+4+....+100=" << Sum<100>::value << endl;
}
  • 數組類模板范例程序
mian.cpp
#include <iostream>
#include <string>
#include "Array.h"
using namespace std;
int main()
{
     Array<int, 5> array;
    for (int i =0;i<array.length();i++)
    {
        array.operator[](i)= i * i;
    }
    for (int i =0;i<array.length();i++)
    {
        cout << array[i] << endl;
    }
    return 0;
}
Array.h
#ifndef _ARRAY_H_
#define _ARRAY_H_
template <typename T,int N>
class Array
{
        T m_value[N];
public:
        int   length();
        bool get_value(int index,T& value) ;
        bool set_value(int index,T value);
        //這個地方需要注意:如果數組類對象要做左值,需要返回一個引用,因為函數調用不能做左值
        //例:  
        //Array<int, 5> array;
        //array.operator[](2)= 3;
        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>::get_value(int index, T& value)
{
        bool ret = (0 <= index) && (index <= N);
        if (ret)
        {
               value = m_value[index];
        }
        return ret;
}
template <typename T, int N>
bool Array<T, N>::set_value(int index, T value)
{
        bool ret = (index >= 0) && (index < N);
        if (ret)
        {
               m_value[index] = value;
        }
        return ret;
}
template <typename T, int N>
T& Array<T, N>::operator[] (int index)
{
        return m_value[index];
}
template <typename T, int N>
T Array<T, N>::operator[] (int index) const
{
        return m_value[index];
}
template <typename T, int N>
Array<T, N>::~Array()
{
}
#endif
  • 小結
  1. 模板參數可以是數值型參數
  2. 數值型參數必須在編譯期間唯一確認
  3. 數組類模板是基於數值型模板實現的
  4. 數組類模板是簡易的線性表數據結構
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM