'Using different array-types interchangeably

I'm sure this question has been answered somewhere, but I'm not sure, what to even search for:

Say I have a class that stores some data in a std::vector, but I want to be able to use two differenct types interchangeably (for example to save memory) depending on the "mode" I set the class to. Something like this:

class MyClass
{
    int Mode; // Could be, say, 0 or 1
    std::vector<float> MyData; // Use this when Mode is 0
    std::vector<short> MyData; // Use this when Mode is 1

    void DoStuffWithData()
    {
        // ...
    }
}

I know, this could probably be done with template, but I have not yet managed to wrap my head around this (if anybody could give me an example, please do so). Of course I could work with overloaded functions and use a lot of if-statements to switch between the cases or use a void-pointer that is set to one of the vectors and then cast to its type, but I think, this would make pretty messy code.

What would be a nice and clean way to use (mostly) the same code by just referring to MyData?

Edit

Mode would change during runtime. Basically the class would record and work with data it collects in the background. I want to be able to just change Mode for a new "recording" (of which I might start multiple during runtime). This would then set both vectors to size zero and use the one selected. Again - I know, I could overload functions and just use some if-statements, but I would like to keep the code short and clean (and maybe learn some things along the way).

c++


Solution 1:[1]

You can't have two members called MyData. You can use templates instead, as that's essentially what they're meant for. This would be a simple example:

template<class T>
class MyClass {
    std::vector<T> MyData;
    void DoStuffWithData()
    {
        // ...
    }
};


int main() {
    MyClass<short> shortData;
    MyClass<float> floatData;
    MyClass<long> longData; // you're no longer limited to just two types
    // ...

    return 0;
}

Notice there's no Mode anymore, as you'll just choose the desired type when declaring each variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Costi Ciudatu