传递到具有不同尺寸的两个维度的相同函数矩阵 [英] Passing to a same function matrices with different sizes of both dimensions
问题描述
我有两个尺寸的不确定大小的常数矩阵,例如
const int denoise [] [3] = {... }
。
const int deconv [] [4] = {...}
然后我定义一个函数 void handleMatrix(const int * const *){...}
希望处理这些矩阵。但它是不正确的。
我尝试使用一个模板:
template< typename Ty> void handle Matrix(const Ty m){...}
p>
但是如何将这些矩阵传递给函数而不使用模板?
p>您应该使用 typedef
,以便您不必使用任何可怕的语法:
using matrix_t = int [3] [3];
您应尽可能通过参考传递您的参数:
void handle_matrix(const matrix_t& mat){
//使用'mat'执行某些操作
}
如果要使用不带 typedef
的原始语法:
void handle_matrix(const int(& mat)[3] [3]){
// ...
}
,如果要使用原始语法并传递指针:
void handle_matrix(const int(* mat)[3]){
// ...
}
但是你失去类型安全,所以我建议反对,只是去与最好的选项: typedef
并通过引用传递。
EDIT
你在@Kerrek SB的回答中说,你的矩阵会有不同的大小。
这里是如何处理和保持nice方法:
template< size_t Columns,size_t Rows&
using matrix_t = int [Columns] [Rows];
template< size_t Columns,size_t Rows>
void handle_matrix(const matrix_t< Columns,Rows& mat){
// ...
}
考虑到我假设你可以在我的答案中使用C ++ 14,如果你留下一个注释,我可以修改任何其他版本。
I have several constant matrices of defferent sizes of both dimensions, say
const int denoise[][3] = {...}
.
const int deconv[][4] = {...}
Then I define a function like void handleMatrix(const int* const*){...}
hoping to handle these matrices. But it is uncorrect.
one effort I tried is using a template like:
template<typename Ty> void handle Matrix(const Ty m){...}
It works perfectly on vs2013.
But how should I pass those matrices to a function without using template?
You should use a typedef
so that you don't have to use any awful syntax:
using matrix_t = int[3][3];
And you should pass your args by reference whenever possible:
void handle_matrix(const matrix_t &mat){
// do something with 'mat'
}
If you want to use the original syntax without a typedef
:
void handle_matrix(const int (&mat)[3][3]){
// ...
}
and if you want to use the original syntax and pass by pointer:
void handle_matrix(const int (*mat)[3]){
// ...
}
But then you lose type safety, so I'd recommend against this and just go with the nicest option: typedef
and pass by reference.
EDIT
You said in a comment on @Kerrek SB's answer that your matrices will be different sizes.
So here is how to handle that and still keep the nice method:
template<size_t Columns, size_t Rows>
using matrix_t = int[Columns][Rows];
template<size_t Columns, size_t Rows>
void handle_matrix(const matrix_t<Columns, Rows> &mat){
// ...
}
Take into account that I'm presuming you can use C++14 in my answer, if you leave a comment I can modify it for any other version.
这篇关于传递到具有不同尺寸的两个维度的相同函数矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!