tags:

views:

218

answers:

5

I'm writing a matrix class, and I want it to be able to store any different (numerical) data type - from boolean to long.

In order to access the data I'm using the brackets operator. Is it possible to make that function return different data types depending on which data type is stored within the class. What's MORE is that I'm not entirely sure how I would STORE different data types within the class under the same variable name. It may well not be possible.

The only way I can think to store the data as any type would be to store it as a void and store the type of data as an extra variable. however RETURNING as a void would cause problems, no? Because I would want to return as the data type I have stored in the function.

Thanks.

+13  A: 

Read up on templates.

Seva Alekseyev
+10  A: 

Your answer is templates!

template <typename T>
class Matrix {
    T* data;
public:
    // ....
    T& operator()( size_t x, size_t y )
    {
     return data[ y*MAXX + x ]; 
    }

}

You can read about templates here.

Kornel Kisielewicz
Thanks. Just a note with your code, is it a typo in your code that you've used the square bracket operator? I don't know if I specified in my post that I was using round brackets (). however I only chose to use them because it appeared that the square bracket operator was only allowed to take a single argument.Is this a mistake on my part?
VolatileStorm
No, you are correct. The code in this answer is wrong.
anon
Yeah, my bad, sorry for the typo.
Kornel Kisielewicz
A: 

Uh, don't you want to use a union (p 841 in C++ 3rd ed)?

"A union is a struct in which all members are allocated at the same address, so that the union occupies only as much space as its largest member".

You're still gonna have to keep track of what kind of union it is though. You might want to embed it in a class or struct to carry a type tag:

struct foo {
   enum types uType;
   union data {
      char *p;
      int i;
      float j;
   }
};
cshapiro
No, you don't want to do that.
anon
Unless the OP needs to store different types within the same matrix - bad idea. It's slow, memory-intensive, and type-unsafe.
Seva Alekseyev
+2  A: 

If all elements of the matrix will be the same type as each other (ie it's a homogenous matrix - so all ints or all floats, etc) then the templated approach is the right way.

If, however, you want to be able to store heterogenous types (ie some ints, some floats, etc) then you'll have to use some sort of variant type. A good example is boost's variant implementation.

You could also just use a union, but you'll probably end up writing much of the infrastructure of variant anyway.

Phil Nash
A: 

Read up on Templates and read this link about Matrix operators from the C++ FAQ

Templates allow you to have a stencil for the content of the Matrix. The operator() implementation, as defined in the C++ FAQ, simplifies your implementation and relieves frustration. :-)

Thomas Matthews