问题
I have different functions for square matrix multiplication depending on matrix size which varies from 8x8 through 20x20. The functions differ from each other because each employ different strategies for optimization, namely, different loop permutations and different loop unroll factors. Matrix size is invariant during the life of a program. My goal is to reduce the time to decide which function must be used. For example, a naive implementation is:
if (matrixSize == 8) C = mxm8(A, B);
else if (matrixSize == 9) C = mxm9(A,B);
...
else if (matrixSize == 20) C = mxm20(A,B);
The time taken to decide which function to use for every matrix multiplication is non-trivial in this case. Can the appropriate function be called right away, perhaps using C++ function templates?
回答1:
If the matrix size is invariant for the life of the program, then you could use std::array
of std::array
for the type of the matrices. Then you could have one multiplication function and overload it for the different types that you support, and the selection will be done at compile time.
You could adapt this approach if you use some custom class for the matrices, and make it a template class where the size is a template parameter.
回答2:
If the matrix size is known in compile time, you could have something like:
constexpr auto matrixSize = 8;
C = mxm<matrixSize>(A, B);
and provide specializations for any known size.
If you do not know the size at compile time, you could anyway have the functions stored in a map, like this:
map<size_t, function<matrix (const matrix&, const matrix&>> multipliers;
multipliers.insert(make_pair(8, mxm8));
and later use something like:
C = multipliers[matrixSize](A, B);
来源:https://stackoverflow.com/questions/32425721/using-c-function-templates-for-a-group-of-functions