Is there a reason for zero sized std::array in C++11?

If you have a generic function it is bad if that function randomly breaks for special parameters. For example, lets say you could have a template function that takes N random elements form a vector:

template<typename T, size_t N>
std::array<T, N> choose(const std::vector<T> &v) {
   ...
}

Nothing is gained if this causes undefined behavior or compiler errors if N for some reason turns out to be zero.

For raw arrays a reason behind the restriction is that you don’t want types with sizeof T == 0, this leads to strange effects in combination with pointer arithmetic. An array with zero elements would have size zero, if you don’t add any special rules for it.

But std::array<> is a class, and classes always have size > 0. So you don’t run into those problems with std::array<>, and a consistent interface without an arbitrary restriction of the template parameter is preferable.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)