The comparison operator==
for std::array
, as provided by the standard library, works only for arrays of equal size. E.g., the following code does not compile
#include <array>
int main()
{
std::array<int, 2> a{1, 3};
std::array<int, 3> b{1, 2, 3};
bool x = (a == b);
}
It seems logical to define a comparison between arrays of unequal size as being always false. By the standard, however, one is not allowed to overload operator==
for the non user-defined types. There is always the option of defining a compare function like
template <typename U, std::size_t N, std::size_t M>
bool compare(const std::array<U, N>& a, const std::array<U, M>& b) noexcept
{
if constexpr (N == M) {
return (a == b);
}
else {
return false;
}
}
Such a solution is unconvenient, since it means that one has to always use the syntax compare(a, b)
when there is the chance that a
and b
have different sizes.
Is there a fundamental reason why the standard library does not define
operator==
as in the code above?Is there a better solution for comparing unequal-sized arrays?