Last active
February 24, 2023 11:27
-
-
Save micjabbour/dbd6d4dae997a155bf5d7cbd4def2d46 to your computer and use it in GitHub Desktop.
(de)serialize enums into QDataStream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef DATASTREAM_ENUM_H | |
#define DATASTREAM_ENUM_H | |
#include <type_traits> | |
//a function that can serialize any enum into QDataStream | |
//it stores the enum in a qint64 | |
template<typename Enum, | |
typename = typename std::enable_if<std::is_enum<Enum>::value>::type> | |
QDataStream& operator<<(QDataStream& stream, const Enum& e) { | |
stream << static_cast<qint64>(e); | |
return stream; | |
} | |
//a function that can deserialize any enum from QDataStream | |
//it reads the enum as if it was stored in qint64 | |
template<typename Enum, | |
typename = typename std::enable_if<std::is_enum<Enum>::value>::type> | |
QDataStream& operator>>(QDataStream& stream, Enum& e) { | |
qint64 v; | |
stream >> v; | |
e = static_cast<Enum>(v); | |
return stream; | |
} | |
#endif // DATASTREAM_ENUM_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QtCore> | |
#include "datastream_enum.h" | |
//an enum class to test the functions | |
enum class E : qint32 { V0, V1, V2, V3, V4 }; | |
int main(int argc, char* argv[]) { | |
QCoreApplication app(argc, argv); | |
QByteArray data; | |
//serialization | |
QDataStream out(&data, QIODevice::WriteOnly); | |
out << E::V1; | |
out << E::V3; | |
//deserialization test | |
E e; | |
QDataStream in(&data, QIODevice::ReadOnly); | |
in >> e; | |
Q_ASSERT(e == E::V1); | |
in >> e; | |
Q_ASSERT(e == E::V3); | |
QTimer::singleShot(100, &app, &QCoreApplication::quit); | |
return app.exec(); | |
} |
Since Qt 5.14 no longer needed.
template <typename T>
typename std::enable_if<std::is_enum<T>::value, QDataStream &>::type&
operator<<(QDataStream &s, const T &t)
{ return s << static_cast<typename std::underlying_type<T>::type>(t); }
template <typename T>
typename std::enable_if<std::is_enum<T>::value, QDataStream &>::type&
operator>>(QDataStream &s, T &t)
{ return s >> reinterpret_cast<typename std::underlying_type<T>::type &>(t); }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks!