Search code examples
c++arraysboostcomparisontype-safety

Comparing arrays of different size


I am implementing my own boost::array variant for fun and education, and I was just wondering: should comparing two arrays of different size yield false, or should it be a type error?

array<int, 3> a = {1, 2, 3};
array<int, 5> b = {1, 2, 3, 4, 5};

a == b   // <--- false or type error?

Solution

  • In the language, the different template instantiations are unrelated types. That means that technically, the simplest thing to do is what boost::array does: ignore the problem, the compiler will yell if you try to compare different sizes.

    I was inclined to answer that this depends on the domain that you are modeling, but given that the array size is a compile time constant, the user should know that both arrays are different without even trying to compare. Even in templated code, as long as there is a single size parameter everything would fall into place by itself.