60_數(shù)組類模板

關(guān)鍵詞:模板參數(shù)類型、數(shù)組類模板實(shí)現(xiàn)

0. 預(yù)備知識(shí)

模板參數(shù)不僅僅是類型參數(shù),也可以是非類型參數(shù)數(shù)值參數(shù)

template
<typename T, int N>
void func()
{
    T a[N];     // 使用模板參數(shù)定義局部數(shù)組
}
// func<double, 10>();

數(shù)值型模板參數(shù)的限制

  • 變量不能作為模板參數(shù)
  • 浮點(diǎn)數(shù)不能作為模板參數(shù)
  • 類對(duì)象不能作為模板參數(shù)
  • ...

本質(zhì):模板參數(shù)是在編譯階段被處理的單元,因此,在編譯階段必須準(zhǔn)確無(wú)誤的唯一確定。

編程說(shuō)明:最高效的方法求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;
}

編程說(shuō)明:數(shù)組模板類

#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

輸出結(jié)果

a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 國(guó)家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說(shuō)閱讀 12,441評(píng)論 6 13
  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy閱讀 9,683評(píng)論 1 51
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,591評(píng)論 19 139
  • 2016年過(guò)去了,新的一年又來(lái)了,去年的家裝行業(yè)發(fā)生了很多事情,但我們還是一直堅(jiān)守在前方。 前陣子,新浪家居出了一...
    好男人_閱讀 576評(píng)論 0 1
  • 中午和姚大管家討論了6號(hào)人的行動(dòng)法則,就是要定目標(biāo),聚焦。那如何聚焦呢,比如,組長(zhǎng)說(shuō)我可以讓自己的文字成為...
    大喵和咸魚閱讀 477評(píng)論 0 3

友情鏈接更多精彩內(nèi)容