Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I initialize a custom Array class by aggregate initialization?

I have my own basic version of std::array

Here’s how it looks:

template<typename T, size_t N> 
class Array {
  public:     
  Array()=default;
  T& operator[](size_t n) {return m_data[n];}     
  size_t Size() {return N;}
  private:     
  T m_data[N]; 
};

I can initialize it this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    Array<int, 3> arr;
    arr[0] = 11;
    arr[1] = 22;
    arr[2] = 33;

But what if I’d like to initialize it in aggregate, like this:

Array<int, 3> arr = { 1, 2, 3 };

How could I go about doing this?

>Solution :

In order for aggregate initialization to work you need to make the class an aggregate class. To achieve this you need to make the array member public. Depending on the standard version you may also need to remove the defaulted default constructor Array()=default; and let it be defined implicitly instead. Don’t declare any constructors at all.

The class will then be an aggregate class and the initialization will then work as shown performing aggregate initialization.

This is also how std::array works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading