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

Time:03-31

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:

    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?

CodePudding user response:

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.

  • Related