Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 253
dexterous Avatar asked Dec 22 '14 14:12

dexterous


2 Answers

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.

  • Boost.Any

  • Boost.Variant

like image 57
lpapp Avatar answered Oct 05 '22 12:10

lpapp


Starting in C++17, there is std::any (may contain a value of any copyable type) and std::variant (may contain a value of any of the given types). These will be supported out of the box in GCC 7, Clang 4.0 and Visual C++ 2017.

Neither of these is entirely equivalent (for example they don't support converting the internal value), but they will allow you to do most of what QVariant does.

like image 43
Leon Timmermans Avatar answered Oct 05 '22 11:10

Leon Timmermans