How should I implement an array constructor that takes in an unknown amount of arguments in c++?

Viewed 153

I am currently implementing a dynamic array which uses a template to identify the type that is stored. However, the problem I am currently having is that I don't know how to make a constructor that accepts as many arguments as the user puts in to initialize the array. Function overloading would not be of any help due to the possibility a function has not been written to accept the user's amount of arguments and it would be a very big design issues.

Below is the class that I am implementing for this dynamic array to help give an idea of what I am trying to create.

template <typename T>
class array
{
    private:

        T *arr;
        int size; //Size of current array
        int items; //items currently in array

    public:

        ~array();
        array();

};
1 Answers

This is an highly simplified case (it doesn't resize), but (I hope) addresses your specific construction question. If you are doing this for exercise you should start with something simpler, like a stack and read all the interesting nuance of exceptions guarantee (there is a beautiful analysis by Sutter on it).

#include <iostream>
#include <initializer_list>
#include <algorithm>

template <typename T>
class array
{
     size_t size; //Size of current array
     int items; //items currently in array
     T *arr;
public:

     //copy and moving semantic omitted

     ~array() { delete[] arr; }
     //use initializer list available from C++11
     array(std::initializer_list<T> init) 
       : size(init.size()), 
         items(init.size()), 
         arr(new T[init.size()])
     {
         std::copy(init.begin(), init.end(), arr);
     }

     //create an array with n elements of a specific value
     array(size_t count, const T& value)
       : size(count), items(count), arr(new T[count])
     {
         std::fill(arr, arr + count, value);
     }

     std::ostream& print(std::ostream& os) const
     {
         for (size_t i = 0; i < size; i++)
             os << arr[i] << " ";
         return os;
     }
};

int main()
{
    array<int> a({1,2,3,4,5,6,10});
    a.print(std::cout);
    array<double> b(5, -1.5);
    b.print(std::cout);
}

Initializer list are supported from C++11.

Some articles:

https://www.stroustrup.com/except.pdf strong exception guarantee vector implementation.

https://ptgmedia.pearsoncmg.com/imprint_downloads/informit/aw/meyerscddemo/DEMO/MAGAZINE/SU_FRAME.HTM Stack exception safety analysis (I remember the book version to be expanded compared to this article)

Please refer to this link for the rule of 0/3/5 What is The Rule of Three?

https://en.cppreference.com/w/cpp/language/rule_of_three

We did have to write the destructor so other (at least) two functions are due.

Related