I have a matrix class that's a template, it used to be
set up like this:
Code:
//matrix.h
template <class T> Matrix
{
public:
Matrix() : m_(0), n_(0), mn_(0) { }
~Matrix();
void size(int rows, int cols)
{
// sets size
}
......
};
then in some other class's h file that wants to use a matrix it's just:
Code:
#include "matrix.h"
class Foo
{
private:
Matrix <double> foo;
Matrix <float> bar;
};
int main()
{
Foo mymatrix;
mymatrix.size(6,1); // old code sets the size this way
....
}
the old design I got with this template was setup so the
"T" array that holds the data is a fixed size and it wastes the
unused part of the array if the user uses less than that number
of elements. I was reading about using template overloading and was
wondering if that would allow creating specific sizes of Matrix's:
Code:
class Foo
{
....
private:
Matrix <double, 6,1> foo; // use the size 6x1
Matrix <float> bar; // use the default storage size
};
by changing Matrix to :
template <class T, int rows = -1, int cols = -1> Matrix
{
};
so that if the optional rows and cols are missing, they're -1.
The default constructor uses the rows*cols to set the
T array size if those optional args are != -1. But the problem
is the compiler is throwing errors when I use something like
Matrix<double,6,1> foo; inside a class and then use a
member function to return that:
Matrix<double> getPositionMatrix() { return foo; }
cartesian_.h: In member function 'Matrix<double, -0x000000001, -0x000000001> Cartesian::getPositionMatrix()':
cartesian_.h:226: error: conversion from 'Matrix<double, 6, 1>' to non-scalar type 'Matrix<double, -0x000000001, -0x000000001>' requested
But, since the 2nd and 3rd arg are optional, how can we
use default template arguments then? Do all the types I have
that are Matrix<T> have to be changed to Matrix<T,int,int> ?
When I try that
Code:
Matrix<double, int, int> getPositionMatrix(void)
{ return positionMatrix; }
I get a different error:
error: type/value mismatch at argument 2 in template parameter list for 'template<class T, int rows, int cols> class Matrix'
cartesian_.h:225: error: expected a constant of type 'int', got 'int'
And another error for the third int optional arg.
Huh? It expected "int" and got "int" so what's the problem?
UPDATE I found a syntax error in the templates, now they compile
ok.
Mark