用于枚举序列化的函数模板
我已经编写了一个函数模板,用于将枚举序列化到我们的流类或从我们的流类序列化枚举(是的,我知道 boost::serialization,但在我的情况下这不是一个选项)。按照我们公司的惯例,枚举被序列化为 int:
template<typename T>
Stream& operator<<( Stream& s, T const& value )
{
s << ( int ) value;
}
template<typename T>
Stream& operator>>( Stream& s, T & value )
{
int v;
s >> v;
value = (T) v;
}
这些是简单的模板,它们在我的用于(反)序列化枚举项向量的函数模板中也能很好地工作。但我担心它们过于通用,即它们也适用于不是 enums
但可以转换为 int 或从
int 转换的类型
。我可以改进枚举序列化模板(或者向量序列化模板)以确保它们仅适用于枚举向量吗?T
I have written a function template for serialization of enums to/from our stream class (Yes, I know boost::serialization, but it is not an option in my situation). Enums by convention in our company are serialized as int
:
template<typename T>
Stream& operator<<( Stream& s, T const& value )
{
s << ( int ) value;
}
template<typename T>
Stream& operator>>( Stream& s, T & value )
{
int v;
s >> v;
value = (T) v;
}
These are simple templates, and they work nicely also in my function templates for (de)serializing a vector of enumeration items. I'm worried though that they are overly generic, i.e. that they get applied also for types T
that are not enums
but can be cast to/from an int
. Can I improve the enum-serialization templates (or maybe the vector-serialization templates) to make sure they only apply to vectors of enum
s?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里需要进行两项改进:并不总是序列化为 int(并非所有枚举都是),而是序列化为任何底层类型。并且,根据您的要求,仅接受枚举。
后者可以使用 std::enable_if 和 std::is_enum 轻松解决:
对于前者,请在函数内执行以下操作:
这需要 C++0x。
如果这不是一个选项,则可以在 Boost 中找到
enable_if
和is_enum
。但是,我认为您需要underlying_type
你自己。 (当然,在最坏的情况下,您可以自己完成这三个操作,但如果我没记错的话,is_enum
可能会很痛苦。)There are two improvements to be made here: not always serializing as
int
(not all enums are), but as whatever the underlying type is. And, as your request, to only accept enums.The latter is easily solved with
std::enable_if
andstd::is_enum
:And for the former, do the following inside the function:
This requires C++0x.
If that's not an option, both
enable_if
andis_enum
can be found within Boost. However, I think you'll need to makeunderlying_type
yourself. (And of course, in the worse case you can do all three yourself, thoughis_enum
can be a pain, if I recall correctly.)