I am trying to write an array class similar to the one in standard lib for practice. I want to be able to initialize my array class by using an initializer list, but I don't what code to add to my class to do that. I am confused because there are multiple elements in the initializer list but only container to hold the data.
#include <iostream>
template<typename T, int size>
class Array
{
private:
T data[size];
public:
Array() {};
};
int main()
{
//I want to do this but it currently doesn't allow me to do this.
//I need someone to tell me what i need to add to my class to be able
//to do this
//Aarray<int, 5> a{1, 2, 3, 4, 5};
//The above line should do
//a.data[0] = 1;
//a.data[1] = 2;
//a.data[2] = 3;
//a.data[3] = 4;
//a.data[4] = 5;
}
There are several ways
make your class aggregate:
template<typename T, int size> class Array { public: T data[size]; };
Provide constructor which accept {..}
such as
template<typename T, int size>
class Array
{
private:
T data[size];
public:
Array(const T (&data)[size]);
//Array(std::initializer_list<T> ini);
// ...
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.