Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / C++
Article

Simple static array class

Rate me:
Please Sign up or sign in to vote.
2.14/5 (3 votes)
20 Mar 2002 63.4K   20   1
A simple static array class that provides range checking and non-zero indexing

Introduction

CStaticArray is a template based class that encapsulates a C style single dimensional static array.

////////////////////////////////////////////////////////
// CStaticArray
// provides:
// 1. Range checking
// 2. Non-zero indexing
// 3. Simple initialisation
////////////////////////////////////////////////////////
template <class T,long cFirstIndex,long cLastIndex>
class CStaticArray
{
public:
    CStaticArray(){}
    CStaticArray(const T& t){Initialise(t);}

    long  GetSize()const    {return cLastIndex-cFirstIndex+1;}
    long  GetFirstIndex()const {return cFirstIndex;}
    long  GetLastIndex()const  {return cLastIndex;}
    bool  IsValidIndex(long nIndex) const 
    { 
        return nIndex>=GetFirstIndex() && nIndex<=GetLastIndex();
    }
    size_t GetNoOfBytes()const  
    {
        return GetSize()*sizeof(T);
    }

    T& operator[](long nIndex)
    {
        ASSERT(IsValidIndex(nIndex));
        return m_Data[nIndex-cFirstIndex];
    }

    const T& operator[](long nIndex)const
    {
        ASSERT(IsValidIndex(nIndex));
        return m_Data[nIndex-cFirstIndex];
    }

    void  Initialise(const T& t)
    {
        for(long i=0;i<GetSize();i++)
            m_Data[i]=t;
    }

    void Initialise(long nStart,long nEnd,const T& t)
    {
        for(long i=nStart;i<=nEnd;i++)
            (*this)[i]=t;
    }

    operator const T*()const {return m_Data;}
    operator T*()            {return m_Data;}

protected:
    T  m_Data[cLastIndex-cFirstIndex+1];
};

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
John Curtis runs Fatlab Software Pty. Ltd. which provides software services to companies in Australia and is currently developing a range of productivity apps.
He has 20+ years experience writing C++ software and can write Java, C#, Javascript when needed!
Specialities include IOT device code, Realtime control, Embedded Linux, Bare bones....

Loves playing with Arduino and Raspberry Pi based solutions for small scale problems.

Comments and Discussions

 
GeneralSTL compiant static array at www. boost.org Pin
Martin Holzherr20-Mar-02 20:51
Martin Holzherr20-Mar-02 20:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.