2

I need to have a QHash container that takes quint8 keys but takes heterogeneous types as values, all of which will be Qt containers or classes. As an example I might want to insert a QDate or QTime object or even quint8 as the value.

How can I define a type like this so I can use it in my other classes and fill appropriately at run time? I want to be able to access it as a global type. Is it possible?

N.B. Question has been edited to better reflect the OP's intent. Answers written before the edit are appropriate to the original question.

Oktalist
  • 14,336
  • 3
  • 43
  • 63
max
  • 2,627
  • 1
  • 24
  • 44
  • You want a `QHash`, nothing to do with templates. – Oktalist Aug 19 '14 at 13:11
  • @Oktalist I wish you had written that as an answer. – max Aug 19 '14 at 13:44
  • I answered the question you intended to ask, not the one you actually asked. :) – Oktalist Aug 19 '14 at 14:08
  • @Oktalist well the question and it's description are open for editing :). In my original description I apologized for my English and failing to describe the problem accurately. What you just mentioned is my intended question. Please edit the question and it's description to reflect this. – max Aug 19 '14 at 14:14

2 Answers2

2

QVariant is a type which can store any of a wide range of value types, determined at runtime, so a QHash<quint8, QVariant> is what you want.

See also https://en.wikipedia.org/wiki/Tagged_union for the general pattern.

Oktalist
  • 14,336
  • 3
  • 43
  • 63
0

The easiest way to do this is inherit from QHash and provide an own template parameter:

template <typename T>
class MyHash : public QHash<quint8, T> { };

Example:

int main(int argc, char *argv[])
{
    MyHash<QDate> testHash;

    quint8 testKey = 123;
    QDate testDate;

    testHash.insert(testKey, testDate);

    MyHash<QDate> testHash2(testHash);

    qDebug() << testHash2.value(testKey); // outputs 'QDate("")'
}

About the placement of this typedef, it's hard to answer that if you don't know the full project.
Just put the definition in the header file which is most suitable in your opinion. Ask yourself if really the whole project needs that definition, or just a couple of files. If you e.g. have a data layer, only your data classes should directly include that file in their header files. Other classes will then automatically know it as soon as they include one of your data class headers.

If really every single class in your project shall use it, you could place it in an existing or a new definitions file in your project root and

  • include that file in your precompiled header file, if you are using that, or
  • check if your compiler supports a "Force Include" option.
Tim Meyer
  • 12,210
  • 8
  • 64
  • 97
  • Actually I want to instantiate an object within my classes without having to specify the type in < > brackets. Just creating an object. Is it possible? – max Aug 19 '14 at 13:09