Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changeable return data type in C++

Tags:

c++

templates

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.

like image 286
V.S. Avatar asked Feb 25 '26 00:02

V.S.


2 Answers

Read up on templates.

like image 161
Seva Alekseyev Avatar answered Feb 27 '26 14:02

Seva Alekseyev


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.

like image 31
Kornel Kisielewicz Avatar answered Feb 27 '26 12:02

Kornel Kisielewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!