I need to be able to retrieve a type based on an ID.
To achieve this, I am intending to create a base class for the types, which declares all the functions as pure virtual functions.
class Base
{
public:
virtual int function1() = 0;
virtual int function2() = 0;
};
I then create derived classes, instantiate these and store the pointers to the instances in an std::unordered_map of base pointers.
std::unordered_map<int, Base*> types;
Each element of the std::unordered_map will point to a different derived class type (i.e. no duplicates).
Then I can retrieve the type I need by getting the associated member from the std::unordered_map.
Base* ptr = types[4];
// Use type...
int num = ptr->function1();
Now I know this could come down to opinion, but is this a horrible use of C++? Is there a cleaner way to do this?
Update
I could use instance of the derived classes instead of their respective IDs, however I would likely have to dynamically allocate each one on the heap (i.e. using new), and I am going to be creating a lot of these, so the overhead from dynamic allocation could have an unwanted effect on performance.
std::tuple<>and then callstd::get<>to give you the instance at the correct index. Then you don't need some horrible inheritance hierarchy enforced on unrelated things..Baseclass seems to be a perfectly standard example of a class meant to be used polymorphically (but add a virtual destructor), and the map is in essence a factory that is perhaps too light on the abstraction (it leaks a lot of information to the user, perhaps that's too much). But on principle it seems OK.