template functions

Hi,

Suppose that I have a matrix template class mat and I would like to create some utility functions for this matrix class... For example, create an identity matrix by just using fmat id = eye(5); (where fmat is typedef for mat<float> and 5 is the number of rows and columns)

I wrote a function template as follows:
1
2
3
4
5
6
7
8
template <class T>
mat<T> eye(const int n) {
   mat<T> e(n,n);
   for (int i=0; i < n; i++ ) {
      e[i][i] = (T)1;
   }
   return e;
}


But when I try to use this function by fmat id = eye(5) (or) mat<float> id = eye(5), it gives me the error "error: no matching function for call to eye(int)". What am I doing wrong? I want to be able to create the identity matrix in all data types.
The concrete problem i see is, that you declare your function to take only const integer. Did you mean to give const references?

Like this works for one of my Matrix Classes i had to make:
1
2
3
4
5
6
7
8
9
10
11
    static Matrix<T, n, m> &eye() {
        T entries[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) 
                if (i == j)
                    entries[i][j] = T(1);
                else
                    entries[i][j] = T(0);
                    
        return *(new Matrix<T,n,m>(entries));
    }


1
2
3
4
5
6
7
int main()
{
    using std::cout;
    using std::endl;

    cout << Matrix<double,3,3>::eye() << endl;
}
(1 0 0; 0 1 0; 0 0 1)
The problem is in the way OP is calling it. The compiler cannot deduce T from OP's line
of code (it cannot deduce T from the lhs of the equals sign). It has to be called like
so:

 
mat<int> = eye<int>( 5 );


But a more useful declaration of eye would be

1
2
template< typename T>
mat<T> eye( T n ) { }


at which point OP can call it the way he was.
Hi,
I understand the error now. However, I prefer the second declaration where I can call it as mentioned before. But, I have another problem then. I can only create int matrices!!

1
2
template <class T>
mat<T> eye(const T n) { }


Should I implement implicit typecast for my matrix class ?? Could this be done in the matrix class definitions?? I am looking for the user to input in the simplest manner. With the above declaration of function, i wouldn't be able to do,
1
2
3
4
// fmat = mat<float>
fmat id = eye(6); // 6 is float here... so, this has to be considered as (int)6
// also, an error check to see if the user provided float input argument
// ex: fmat id = eye(6.5); 

May be therefore, its better to implement just for int case and implement a typecast?
thank you.
okay, that was a stupid question! :) please ignore it. I have implemented it as mat<T> eye(const T n) { }. In addition, I also managed to implement the typedef I will require them anyways.

thank you.
Topic archived. No new replies allowed.