std::initializer_list is a class type which is commonly used with constructor to pass initializer list as argument. For example:
#include <iostream>
class IntArray
{
int *m_arr{};
int m_length{};
public:
IntArray() = default;
IntArray(int length)
: m_length{length}
{
m_arr = new int[static_cast<std::size_t>(length)];
}
IntArray(std::initializer_list<int> list)
: IntArray(static_cast<int>(list.size()))
{
std::copy(list.begin(), list.end(), m_arr);
}
int *begin() const
{
return m_arr;
}
int *end() const
{
return m_arr + m_length;
}
friend std::ostream &operator<<(std::ostream &out, const IntArray &arr)
{
out << '[';
for (const int &value : arr)
{
out << value << ',';
}
out << ']';
return out;
}
};
int main(int argc, char const *argv[])
{
std::initializer_list<int> a{1, 2, 3, 4};
std::cout << *a.begin() << '\n';
IntArray arr{1, 2, 3, 4, 5};
std::cout << arr << '\n';
return 0;
}This enables us to use our custom IntArray with initializer list. When compiler encounters initializer list, it converts the list to std::initializer_list object and we already defined a constructor with parameter matching the datatype, the constructor gets used to create the array.