Jason
Jason

Reputation: 2298

How to create a std::array wrapper class

Background:

I'm trying to create a few of my own wrapper classes for the STL containers so I can separate implementation from my code base. I have already done alittle bit with my Vector class wrapper like so:

Vector.h

template<typename type>
    class Vector
    {
    public:
        Vector();
        Vector(std::initializer_list<type> initializer);
        Vector(int size, int defaultValue);
        Vector(int size);
        ~Vector();

        void PushBack(type itemToPushBack);
        type AtPosition(int position);

    private:
        std::vector<type> m_collectionOfItems;
    }; 

As you can see, I have constructors setup and I've used std::vector as a member so that I can just call std::vector functions within my own Vector classes.

Issue:

With std::array I have to specificy a size immediately when instantiating any object. So if I created a member variable like I did with my vector class, I would have to give that array object a size. I would rather the size be specified by the user using some similar constructor setup to Vector's (ex. MyArrayClass myArray(10) ). How might I try and implement this Array wrapper?

Upvotes: 1

Views: 1351

Answers (1)

Arun
Arun

Reputation: 20383

I would rather the size be specified by the user using some similar constructor setup to Vector's (ex. MyArrayClass myArray(10) ). How might I try and implement this Array wrapper?

The purpose of std::array, unlike std::vector, is that the size is specified at compile time. Its underlying structure is a plain vanilla array which needs the size at compile time.

I can think of the following wrapper in case it is useful

template <typename T, std::size_t N>
class Array {
  public:
    // stuff
  private:
    std::array<T, N> array_;
};

Upvotes: 1

Related Questions