vendredi 8 avril 2022

How do i use deduction to choose the return type of function

I have a question regarding the full deduction with functions using C++11 standard. Basically I am ought to make a function that takes a single parameter that should look like a matrix (basically any container) whose elements can again be any container but having in mind that elements of every row do not necessarily need to be the same size. For an example the parameter could be vector of deques, classic C-like matrix, vector of vectors, deques of vectors and so on, you get the point. Having said that. Function itself needs to dynamically alocate (using fragmented and not continual allocation) memory for 2d matrix with same structure and type of elements and then copy all the elements from given matrix into it, and finally return a double pointer which you can use to access the elements of matrix. Having that said, I do not actually know how to use full deduction so that the function actually knows which type is the double pointer that it must return. First thing that crosses my mind is to use something like this:

template <typename MatrixType>
auto CreateMatrix (MatrixType M) -> decltype ... 

Logic behind it is that full deduction would find out what type of double pointer must be returned, but the three dots (...) is where im halted, i dont actually know what to write there.

Ofcourse I could probably do something like this:

template <typename MatrixType>
MatrixType** CreateMatrix (MatrixType M) 

But it doesn't use deduction because call like this:

std::vector<std::deque<double>> a = {...};
auto x = CreateMatrix(a);

wouldn't work without using <double> with the call of the function, so it is not a full "problem solved" it is just a cheap trick.

Memory allocation shouldn't be hard, I think It would be pretty easy to do, but currently I'm stuck here and do not know what to do.

I am grateful for every help!

Aucun commentaire:

Enregistrer un commentaire