Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c++ - Passing to a same function matrices with different sizes of both dimensions

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...