简体   繁体   中英

Change input type of a function

I have a simple function in c++ to do matrix multiplication. I have defined the function as follows:

void matrix_multiplication(std::vector<std::vector<double> > matrix1 , std::valarray<std::valarray<double> > matrix2,
                       std::vector<std::vector<double> > &result)

Now in some different part of the code, I again need to call this exact same function but with different input types ie with vectors. Rather than defining another function like below that does the same job as matrix_multiplication:

void matrix_multiplication2(std::vector<double>matrix1 ,std::valarray<double> matrix2,
                           std::vector<std::vector<double> > &result)

I would like to ask if it is possible to somehow change the input type in two different calls of a function.

Realistically, you have a few options:

1) Overload your method to accept the correct arguments. This use case is precisely why we have function overloading to begin.

2) Convert your arguments before passing them in to your existing function. This is kind of ugly and, if it's done several times, could end up looking pretty messy.

3) Actually write (or find) a Matrix library and avoid this problem altogether. This is my preferred solution, but, without knowing the domain over your problem, may be overkill.

"I would like to ask if it is possible to somehow change the input type in two different calls of a function. "

You can make that function a template (supposed all of the operations of the parameters will work equally for any container type passed):

template<typename Container, typename ValArray>
void matrix_multiplication( Container matrix1
                          , ValArray matrix2
                          , Container &result) {
    // Implementation ...
}

Take a look at templates in c++, it allows you to do such things in c++. You can write a template generic function, then write specialization for each type depending on your needs.

take a look at this tuto :

http://www.cplusplus.com/doc/tutorial/templates/

The short answer is to use templates:

template <typename T>
void matrix_multiplication(std::vector<std::vector<T> > matrix1 , std::valarray<std::valarray<T> > matrix2,
                   std::vector<std::vector<T> > &result)

Generic programming FTW! However, you are re-inventing the wheel here...writing a good generic library is HARD, and linear algebra is harder, and not as trivial as you think. I suggest Eigen or Armadillo. I mean, based on your function alone I can guess you have a O(n^3) solution to the multiply, when the most efficient are less than that, see http://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM