在C ++ 64位枚举?

2023-09-07 23:34:57 作者:落颜

有没有办法有一个64位的枚举在C ++?虽然重构了一些code我碰到一堆#define语句中这将是更好,因为一个枚举,但大于32位将导致编译错误。

出于某种原因,我认为以下可能的工作:

 枚举MY_ENUM:无符号__int64
{
    LARGE_VALUE = 0x1000000000000000,
};
 

解决方案

我不认为这是有可能用C ++ 98。枚举的基础再presentation要由编译器。在这种情况下,你最好使用:

 常量__int64 LARGE_VALUE = 0x1000000000000000L;
 

由于C ++ 11,可以使用枚举类指定枚举的基本类型:

 枚举类MY_ENUM:无符号__int64 {
    LARGE_VALUE = 0x1000000000000000ULL
};
 
C语言的位段与枚举详解

此外枚举类引入一个新的命名适用范围。因此,而不是指 LARGE_VALUE ,你将引用 MY_ENUM :: LARGE_VALUE

Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.

For some reason I thought the following might work:

enum MY_ENUM : unsigned __int64  
{  
    LARGE_VALUE = 0x1000000000000000,  
};

解决方案

I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using:

const __int64 LARGE_VALUE = 0x1000000000000000L;

As of C++11, it is possible to use enum classes to specify the base type of the enum:

enum class MY_ENUM : unsigned __int64 {
    LARGE_VALUE = 0x1000000000000000ULL
};

In addition enum classes introduce a new name scope. So instead of referring to LARGE_VALUE, you would reference MY_ENUM::LARGE_VALUE.

相关推荐