如何安全地将整数类型转换为作用域枚举 [英] How to safely cast integral types to scoped enums
问题描述
C ++ 11
作用域枚举很棒,您应该尽可能使用它们。
但是,有时您需要将整数转换为有范围的枚举值(例如,是否从用户输入中获取)。
C++11
scoped enums are great, you should use them whenever possible.
However, sometimes you need to convert an integer to a scoped enum value (say if you are getting it from user input).
有一种安全的方法这样做并检测该值何时无效(即,超出枚举的允许值)?
Is there a safe way to do this and detect when the value is not valid (i.e., outside the permitted values of the enum)?
我相信,如果使用整数,则仅使用static_cast会导致未定义的行为无效。是否有一种通用的方法不需要手动为每种作用域枚举类型编写转换函数(并且每次向枚举添加新值时都需要更新)?
I believe just using static_cast leads to undefined behavior if the integer is not valid. Is there a generic way of doing that does not require writing a conversion function for each scoped enum type by hand (and that needs to be updated every time you add a new value to the enum)?
推荐答案
一种常用的方法是在枚举中包含结束标记
A common way to do that is to include in your enum an ending marker
enum class Colors : char
{
Red,
Green,
Blue,
Last_Element
}
使用这种方法,在转换时,您可以检查使用的值是否小于Last_Element的值。
Using this approach, when converting, you can check if the value you're using is less than the value of Last_Element.
请考虑以下功能:
template<typename T>
typename std::enable_if<std::is_enum<T>::value, bool>::type
IsValidEnumIntegral<T>(int integral)
{
return (int)(T::Last_Element) > integral;
}
,您可以像这样使用它:
and you could use it like so:
if(IsValidEnumIntegral<Colors>(2))
//do whatever
这适用于您使用称为Last_Element的元素进行的任何枚举。您可以进一步创建类似的功能,然后为您自动转换。
This would work for any enum you made with an element called Last_Element. You could go further to create a similar function to then auto-convert for you.
注意:未经测试。我目前无法这样做,但我认为这可能有效。
Note: This is not tested. I am not in a position to do so at the moment but I think this could work.
编辑:仅当枚举有效时,此方法才有效有问题的是使用一组整数,其元素之间没有间隔。提供的函数还将假定枚举不包含负整数,尽管可以轻松地向其添加First_Element。
EDIT: This will only work if the enum in question uses a set of integers with no gaps for its elements. The function provided will also assume the enum does not contain negative integers, though a First_Element can easily be added to it.
这篇关于如何安全地将整数类型转换为作用域枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!