0

I am currently working on a project where I have a situation I am trying to solve. I have a base class that has a QHash that stores some objects. Currently I have two derived classes. The problem is that for one derived class I would like the key to be a string and for the other I would like it to be an int. The logic in the base class will be the same regardless, just the key type is different. I know that the simplest answer is to just make the key a string and convert the int to a string in that derived class when I access it. I was trying to come up with a more elegant solution, but maybe thats just overthinking it.

A lot of the access happens through functions, but sometimes the derived class accesses the QHash directly. That could be changed though. I thought about overriding the calls in the derived class to accept an integer, then convert it and call the base class version.

I wasnt sure if there was any way to make the base class QHash have a generic key. The functions all take the key too, so they would have to follow the same pattern.

thecaptain0220
  • 2,098
  • 5
  • 30
  • 51
  • 1
    Does the hash really need to be a member of the base class? You could have each derived class having it's own has, and just give them a common interface. – NathanOliver Dec 11 '18 at 17:57
  • The reason I created the base class was to move a lot of common functionality of the two derived classes there. Most of that is acting on the objects in the QHash. Is it possible to have the QHash declared in the derived classes and still access it in the base class? – thecaptain0220 Dec 11 '18 at 18:03
  • QVariant as key? – FrozenM Dec 11 '18 at 18:22
  • 1
    I checked and QHash doesn't allow QVariant as the key. That would be perfect. In C# you could just make it an object type and not worry about the type of the key. This is what I was trying to replicate, but cant see a way to do it. – thecaptain0220 Dec 11 '18 at 18:25
  • Although, I might be able to make the functions take a QVariant and just use toString when I access the QHash. – thecaptain0220 Dec 11 '18 at 18:27
  • 1
    If you only use the baseclass for common functionality, why not make the base class a template itself? Make the key the template parameter and set it when inheriting the base class – Felix Dec 12 '18 at 00:36

0 Answers0