Reputation: 3014
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.
Upvotes: 2
Views: 630
Reputation: 57625
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.
Upvotes: 10
Reputation: 22493
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.
Upvotes: 2