Is there any way I can change the value of a template parameter inside the templated object or are these values constant. i.e.

template<int width, height>
class matrix {
............
}

void matrix<width,height>::setSize(int w,int h) {
     width = w;
     height = h;
}

Recommended Answers

All 8 Replies

when you declare the class you can do this

template<typename T, typename T>
class matrix
{
//...
// or
template <typename T, typename C>
class matrix
{
//...

the first example both numbers passed will be the same type that you chose the second example the first and second term can be different ie. <int, double> <short, long> etc.

Not really the answer to what I was asking. so my template is:

template<int height, int width> matrix {..........}

I declare the object like this

matrix <3,3> foo

The numbers defined in the template will determine the size of the 2d array inside the object. so the matrix I declared is a 3x3 matrix. If I want to make foo into a 4x4 I would like to call foo.resize(4,4) where the method would set the template parameters from <3,3> to <4,4>.

Is this possible. Or do I have to delete the object and redeclare the with the new parameters I would like.

why are using a template for this application? you could just pass the values into the constructor in the matrix class and have a resize function built in if you need to change it. templates are used to make functions or classes that can have or use different types and are used instead of having to write a function or class for each different type.

Template parameter are instantiated pre-runtime. So when your program is running, you cannot change them.

If you are making a Matrix class, why don't you consider vector or vectors as the backend data structure. Then make your own resize function. Alternatively, you can create a copy constructor. Then, when you wish to resize the object, create a bigger new object, copy to it the content of original object and destroy the former.

why are using a template for this application? you could just pass the values into the constructor in the matrix class and have a resize function built in if you need to change it. templates are used to make functions or classes that can have or use different types and are used instead of having to write a function or class for each different type.

Yea I was just thinking of that. I would defiantly be easier doing it that way. I was doing it the template way so that I could make some predefined tyedef'd matrices that the user could call quickly and load their data into.

no prob happy to help if you have any other errors or logic faults let me know nd ill happy to help.

>>why are using a template for this application?
Perhaps to save the run-time

Yea that too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.