【发布时间】:2019-05-31 23:42:53
【问题描述】:
我正在尝试序列化和反序列化(使用QDataStream,但这在这里无关紧要)enum class 变量:
enum class Type : char
{
Trivial,
Complex
};
序列化很简单:
QDataStream &operator<<(QDataStream &stream, Type type)
{
return stream << static_cast<char>(type);
}
但是反序列化不是:
QDataStream &operator>>(QDataStream &stream, Type &type)
{
return stream >> static_cast<char &>(type);
}
显然,引用enum class 的static_cast 对其基础类型的引用是不允许的。此外,“明显”的解决方案:
QDataStream &operator>>(QDataStream &stream, Type &type)
{
return stream >> reinterpret_cast<char &>(type);
}
实际上可能是非法的并且没有由标准according to the answer to this question 定义,因为等效表达式return stream >> (*static_cast<char *>(static_cast<void *>(&type))); 在那里被声明为非法(或者更确切地说,标准没有定义)。如果是这种情况,我需要这样做:
QDataStream &operator>>(QDataStream &stream, Type &type)
{
char c = 0;
stream >> c;
type = static_cast<Type>(c);
return stream;
}
这不漂亮,是 4 行而不是 1 行等等。对于这样一个(看似)简单的事情,我觉得这很不必要。
我的问题:当将对enum class 变量的引用转换为其基础类型的引用时,reinterpret_cast 或通过void* 等效的static_cast 是否真的非法(标准未定义)?
【问题讨论】:
-
您提出的问题与您链接的问题有何不同? (我可能遗漏了一些东西......)问“链接问题的答案真的正确吗?”很可能会将您标记为重复。
-
通常我会避免像瘟疫这样的巧妙技巧,并认为 reinterpret_cast 充其量只是一种代码味道。 4行版本有什么问题?它很容易理解,无论如何编译器都会对其进行优化......
-
@jakub_d 链接的问题(及其答案)与在转换后操纵值(递增)有关。我的问题纯粹是关于演员的。尽管链接问题的答案似乎也回答了这个问题,但对我来说有点过于法律,因此这个问题。我也尽量避免
reinterpret_cast,但例如你不能用 SIMD 和其他东西来避免它。 -
我认为在强制转换值上调用运算符 >> 也可以称为操作。律师的东西也适用于你的案子。因此,就标准而言,它不能保证有效。
标签: c++ qt5 enum-class qdatastream