这个片段是一个来自c++20代码库的小例子。它是一个用于将矩阵相乘的自由函数。矩阵本身在
完整的类型名称变为
在现代C++中有哪些语法或策略可用于减少重复的类型名称的噪音?
ROWS
和COLUMNS
上进行了模板化处理,就像std::array
一样,在函数接口中使用起来有点麻烦。完整的类型名称变为
Matrix<ROWS, COLUMNS>
,这本身没问题,但当重复三次(对于返回值和两个参数)时,它确实影响了函数接口的可读性。在现代C++中有哪些语法或策略可用于减少重复的类型名称的噪音?
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;
}
要求:
- 所有矩阵(参数和返回值)必须具有相同的维度。
- 矩阵知道自己的大小(
.columns()
,.rows()
),因此在这些循环中我们不需要使用模板参数。 - 矩阵还提供了一个
::size_type
,所以理想的解决方案应该让我们可以(干净地)使用它,而不是在循环中硬编码uint8_t
。
auto operator*(const Matrix<ROWS, COLUMNS>& lhs, decltype(lhs) rhs)
- 273Kmatrix
的概念,然后类似于template <matrix LHS, std::same_as<LHS> RHS> LHS operator*(const LHS& lhs, const RHS& rhs)
。 - 康桓瑋for(LHS::size_type row = 0; row < lhs.rows; row++) ...
。此外,使用uint8_t
作为索引听起来像是等待溢出的事情。 - Passer Bytemplate <uint8_t ROWS, uint8_t COLUMNS> class Matrix{... friend Matrix operator*(Matrix const& lhs, Matrix const& rhs) { ... } };
,请参阅此处(2):https://en.cppreference.com/w/cpp/language/friend - fabian