Overloading class template parameters

I'm trying to wrap my head around why there is a problem compiling this

#include <iostream>
template <unsigned int ROWS,unsigned int COLS>
class Matrix{
    public:
        double dotProd(const Matrix<1,COLS>& other){
            static_assert(ROWS==1,"dotProd only valid for two vectors");
            return COLS;//place holder for dot product with row vectors
        }
        double dotProd(const Matrix<ROWS,1>& other){
            static_assert(COLS==1,"dotProd only valid for two vectors");
            return ROWS;//place holder for dot product with col vectors
        }
};
int main(){
    Matrix<1,32> bob;
    Matrix<1,32> fred;
    std::cout<<bob.dotProd(fred)<<std::endl;
    return 0;
}

which gives me this error:

overloadedTemplateMethod2.cpp: In instantiation of ‘class Matrix<1u, 1u>’:
overloadedTemplateMethod2.cpp:17:32:   required from here
overloadedTemplateMethod2.cpp:9:16: error: ‘double Matrix<ROWS,COLS>::dotProd(const Matrix<ROWS, 1u>&) [with unsigned int ROWS = 1u; unsigned int COLS = 1u]’ cannot be overloaded
     double dotProd(const Matrix<ROWS,1>& other){
            ^
overloadedTemplateMethod2.cpp:5:16: error: with ‘double Matrix<ROWS, COLS>::dotProd(const Matrix<1u, COLS>&) [with unsigned int ROWS = 1u; unsigned int COLS = 1u]’
     double dotProd(const Matrix<1,COLS>& other){
            ^

I understand that the template populating the parameters will force the second function to allow double dotProd(const Matrix<1,1>& other), but I think the other should enable again double dotProd(const Matrix<1,32>& other), not Matrix<1,1>.

what's going on here?

+6
source share
1 answer

When you do this:

bob.dotProd(fred)

Functions dotProdare created to allow the call to Matrix<1,32>.
We can say that (disclaimer: this is not exactly how it works, but it gives an idea of ​​what is happening under the hood), they are ultimately declared as:

double dotProd(const Matrix<1,32>& other);
double dotProd(const Matrix<1,1>& other);

. Matrix, : Matrix<1,1>.
​​, dotProd, ?

double dotProd(const Matrix<1,1>& other); // Matrix<1, COLS>
double dotProd(const Matrix<1,1>& other); // Matrix<ROWS, 1>

, . , .

​​ , main :

 Matrix<1,1> someone;

, Matrix , COLS ROWS .

+4

All Articles