I wrote a template that correctly deduces the size of a square matrix. I got this from looking for online solutions, but not sure I understand the inner workings of the template. The purpose of the template function is to compare two square matrices of the same size to verify that they are nearly equal.
template<typename T, int N>
void
CompareRMatrixResults(T (&R)[N], creal_T M[4][4])
For the first argument, I pass in either a 2×2 or a 4×4 square matrix. For the 2nd argument, I pass in a 4×4 matrix whose elements are of type creal_T
. (Due to the way the data is set up, if N = 2, then M is treated as a 2×2 matrix in the body of the function.
Why is the &
needed in (&R
)? Are there other signatures that also work? Please explain how to interpret (&R)[N]
and why I don’t need [N][N]
since the 2d array is square. How does N get deduced with this template?
I got the idea for this template by searching and found numerous links including:
https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
Converting multidimensional arrays to pointers in c++
https://www.codeproject.com/articles/295853/obtaining-the-size-of-a-cplusplus-array-using-te-2
But although I got a recipe for doing 2d array deduction, I don’t have a good sense of how it works.