对一组函数使用C ++函数模板 [英] Using C++ function templates for a group of functions

查看:130
本文介绍了对一组函数使用C ++函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据从8x8到20x20不等的矩阵大小,我有不同的方矩阵乘法的函数。函数彼此不同,因为每个函数采用不同的优化策略,即不同的循环排列和不同的循环展开因子。矩阵大小在程序的生命期间是不变的。我的目标是减少决定必须使用哪个函数的时间。例如,一个朴素的实现是:

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);

决定在每种矩阵乘法中使用哪个函数的时间在这种情况下是非常重要的。可以立即调用相应的函数,可能使用C ++函数模板?

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?

推荐答案

如果矩阵大小是不变的程序,那么您可以使用 std :: array std :: array 作为矩阵的类型。然后你可以有一个乘法函数,并为你支持的不同类型重载它,并且选择将在编译时完成。

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.

这篇关于对一组函数使用C ++函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆