C++ runtime polymorphism or template type selection

Viewed 48

I have a binary file I want to read and in that file, the datatype of the stored data is encoded as a number in the beginning. Therefore I will need to - at runtime - when reading the file, create an object of a class with that specified type and store the data in it.
The problem I'm having is that for templates the type needs to be known at compile time which it isn't. I do however know what the possible types are so it doesn't need to be completely generic (Let's say int and float).
My other approach was using polymorphism like this

#include<iostream>
using namespace std;

struct Parent {
    virtual void get_type();
};

template<class T>
struct Child : public Parent{
    // T data;

    void get_type() {
        cout << typeid(T).name() << endl;
    }

    // T& get_data() {
    //     return data;
    // }
};

Parent* Factory(int in) {
    if (in == 0) {
        return new Child<int>;
    } else {
        return new Child<float>;
    }
}


int main() {
    int in;
    cin >> in;

    Parent* p = Factory(in);
    
    p->get_type();
    delete p;
}

However, the currently commented out part will not work because it needs to be a virtual function of a Parent who doesn't know of T.
Another solution would be to create the object inside an if statement. I do however need it to live longer than the scope of it. I have also looked into std::variant but that seems too complicated for my needs.

I was wondering if there is an (easy) way to create the object/class with a chosen at runtime datatype out of a list of two to five types, that still allows me to access the data in the class using standard getter- and setter-methods.

0 Answers
Related