I am trying to create a sample array class which is initialiszed by a std::initializer_list. I would like to check if the size of the initializer list is not more than the size of the array during compile time. Since static assert can only evaluate constexpr, this code is not getting compiled.
#include<initializer_list>
#include<cstddef>
template <typename T , size_t _size>
class array
{
private:
T arr[_size];
public:
array()
{
}
array(std::initializer_list<T> arrList)
{
static_assert(_size>arrList.size(),"too many initializers"); // error: non-constant condition for static assertion
}
~array()
{
}
};
int main()
{
array<int,4> arr = {1,2,3,4,5};
return 0;
}
std::array already has this functionality, but i couldnt find its implementation in header file.
#include<array>
int main()
{
std::array<int,5> arr= {1,2,3,4,5,6}; // error: too many initializers for ‘std::array<int, 5>’
return 0;
}
arrayit is not explicitly implemented.arrayuses aggregate initialization and there the compiler takes care, not the STL.