sergej.p
sergej.p

Reputation: 115

C++ vector constructor implementation

How do I make it possible to call the following construct for my vector class?

vector <int> v{1,2,3};

how to properly declare such a method?

My source code:

template<typename T>
class my_vector {
    T* values;
    std::size_t values_num;
    std::size_t max_size;

    public:
        explicit my_vector(std::size_t size);
        ~my_vector();

        void push_back(const T& value);
        std::size_t size();
        T operator[](int pos);
        T at(int pos);
};

Upvotes: 1

Views: 279

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275500

The easy way is a constructor taking a std::initializer_list<T>.

Another way is writing a template constructor, a bit like this:

template<class...Ts> requires (std::is_same_v<T, Ts> && ...)
explicit my_vector(Ts...ts);

but getting that just right is a pain, so just go with initializer_list.

Upvotes: 3

Related Questions