c++qtstlqtcoreqvariant

What is the equivalent of QVariant in C++?


I am trying to port a Qt application to C++ using STL. What is the equivalent of QVariant in C++? QVariant can store any data type - a container that holds heterogenous - different types of objects. However, I have to port this application to C++. What is the equivalent of QVariant in C++?


Solution

  • What is the equivalent of QVariant in C++?

    The equivalent in C++ is called QVariant.

    Semi-joke aside, it is probably the closest to union, but QVariant is so much more than that; meta types, CoW, etc.

    Actually, sharing implicitly is forbidden these days in STL, so that is another reason why you would not find anything like this off-hand.

    I would suggest to make notes to yourself what functionality exactly you need from a QVariant and make a judgement call whether it is actually worth dropping QtCore.

    This is just a friendly reminder from the documentation:

    The QVariant class acts like a union for the most common Qt data types.

    Because C++ forbids unions from including types that have non-default constructors or destructors, most interesting Qt classes cannot be used in unions. Without QVariant, this would be a problem for QObject::property() and for database work, etc.

    However, since C++11 types with constructors and destructors are allowed. You have another question in here to ask from yourself:

    Do I want to support everything that Qt does or am I happy to require at least C++11?

    To be fair, you could also look into the following boost variants below, but then you end up using boost instead of QtCore after the porting.

    This is another judgement call for yourself. They are not replacements for each other, neither technically, nor compatibility wise.

    Boost in this case is a build time dependency, while QtCore is a runtime. Qt would guarantee binary (and source) compatibility during the life cycle of the same major version, while boost may not do the same for such a long period as QtCore does.

    Either way, none of these options are pure STL solutions in the end of the day the way I think you wanted it to.