c ++ 11 vs c ++ - 枚举差异

Unk*_*337 3 c++ enums c++11 strongly-typed-enum

//c++03
enum Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT];

//c++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[(int) Something::SCOUNT];
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何在不将枚举计数转换为int的情况下使用枚举?

ole*_*ard 10

在这种情况下如何在不将枚举计数转换为int的情况下使用枚举?*

你不能...但是你可以删除classenum class

class关键字意味着你不能含蓄地之间进行转换enum,并int取出class关键字意味着你enum以同样的方式将工作在C++的早期版本.你不需要演员阵容,但是strongly typed enums通过允许隐式演员表达到整数值你会失去安全感.

//C++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT]; // ERRROR

//C++11
enum Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT]; // OK
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多信息strongly typed enums


另一种选择是投射它,就像你正在做的那样.但是你应该避免使用旧的C-style cast并使用,static_cast<>因为它具有更好的类型安全性并且更明确.

//C++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[static_cast< size_t > ( SCOUNT ) ]; // OK
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 5

实际上在第二种情况下,你不能在没有强制转换的情况下写出来.

由于你必须使用强制转换,你现在可以做的是使用更好的强制转换而不是c-style强制转换:

int arr[to_integral(Something::SCOUNT)];
Run Code Online (Sandbox Code Playgroud)

其中to_integral定义为:

#include <type_traits> //it is where std::underlying_type is defined

template<typename E>
constexpr auto to_integral(E e) -> typename std::underlying_type<E>::type 
{
   return static_cast<typename std::underlying_type<E>::type>(e);
}
Run Code Online (Sandbox Code Playgroud)

现在这个功能模板是可重用的.您可以使用任何C++ 11样式的枚举类型.它还推断了基础类型,因此您不必再在代码中提及了.有关详细说明,请参阅此答案.