Thursday, July 9, 2009

Help with syntax in c++?

i'm trying to write a matrix class for c++. but i'm a bit rusty, and I don't have access to my text book, so i need some help refreshing my memory on a few basics.





so far i've been able to declare and implement the following function in my program file, but can't get it to compile when i declare it and define it in a header and definition file.


this is part of my header file:


template %26lt;class itemType%26gt;


class apmatrix


{


public:


// constructors/destructor etc...





private:


apmatrix%26lt;int%26gt; GenerateIdentity(int row, int col);


// etc etc





this is part of my apmatrix.cpp file:





template %26lt;class itemType%26gt;


apmatrix%26lt;itemType%26gt;::


apmatrix GenerateIdentity(int row, int col)


{


apmatrix%26lt;int%26gt; temp(row, col, 0);


for (unsigned i = 0; i %26lt; ((row %26lt; col) ? row: col); ++i)


temp[i][i] = 1;


return temp;


}





by changing it to a public function, i've been able to compile my program, so long as i don't call the member function.

Help with syntax in c++?
You cannot put template functions in the .cpp file, they have to be in the header. When a template is instantiated with a specific type, it needs to see the entire definition of the template. Any template code in a separate cpp file is not seen. In short, you don't use any .cpp file for your template class, just one big header.





As a second problem, some compilers do not support template member functions (this may not be a problem for you).





As a separate design issue, GenerateIdentity should be a static class function. It doesn't operate on a specific matrix object, it just generates a new one.





The declaration should be:


template %26lt;class itemType%26gt;


apmatrix%26lt;itemType%26gt;


apmatrix %26lt;itemType%26gt;::GenerateIdentity (int row, int col)





One small bug:


apmatrix%26lt;int%26gt; temp(row, col, 0);





This should be


apmatrix%26lt;itemType%26gt; temp(row, col, 0);
Reply:Your GenerateIdentity declaration in the source file is malformed.





It should be:





template %26lt;class itemType%26gt;


apmatrix%26lt;int%26gt; apmatrix%26lt;itemType%26gt;::GenerateIdentity(int... int)


{


...


}








As mentioned below, most compilers don't like having template definitions in a separate source file. GCC is ok with it if you use the appropriate flags, but many IDEs will give you the undeclared function error.

bouquet

No comments:

Post a Comment