This snippet is a small example from a c++20 code base. It is a free function to multiply matrices with each other. The Matrix itself is templatized on ROWS
and COLUMNS
which, like the std::array
, makes it a bit painful to use in function interfaces.
The full type name becomes Matrix<ROWS, COLUMNS>
which is fine on its own, but when repeated three times (for the return value and two arguments) it really harms the readability of the function interface.
What syntax or strategies are available in modern C++ to make the repeated type name less noisy?
template <uint8_t ROWS, uint8_t COLUMNS>
Matrix<ROWS, COLUMNS> operator*(
const Matrix<ROWS, COLUMNS>& lhs,
const Matrix<ROWS, COLUMNS>& rhs) noexcept
{
Matrix<ROWS, COLUMNS> result;
for (uint8_t row = 0; row < ROWS; ++row)
{
for (uint8_t col = 0; col < COLUMNS; ++col)
{
for (uint8_t i = 0; i < COLUMNS; ++i)
{
result(row, col) += lhs(row, i) * rhs(i, col);
}
}
}
return result;
}
Requirements:
- all Matrixes (arguments and return value) must have the same dimensions
- The Matrix knows its own size (
.columns()
,.rows()
), so we don't need to use the template arguments in those loops. - the Matrix also offers a
::size_type
so the ideal solution would let us use that (cleanly) instead of hardcodinguint8_t
in the loop.