有没有办法让`enum`类型无符号?

时间:2010-04-28 18:15:56

标签: c++ enums

有没有办法让enum类型无符号?以下代码向我发出有关签名/未签名比较的警告。

enum EEE {
    X1 = 1
};

int main()
{
    size_t x = 2;
    EEE t = X1;
    if ( t < x ) std::cout << "ok" << std::endl;

    return 0;
}

我试图使用以下内容强制编译器使用无符号底层类型进行枚举:

enum EEE {
    X1 = 1,
    XN = 18446744073709551615LL
    // I've tried XN = UINT_MAX (in Visual Studio). Same warning.
};

但是仍然会发出警告。


将常量更改为UINT_MAX使其在GNU C ++中工作,应该符合标准。似乎是VS中的一个错误。感谢詹姆斯提示。

6 个答案:

答案 0 :(得分:8)

您可以尝试:

enum EEE {
    X1 = 1,
    XN = -1ULL
};

如果没有U,则会对整数文字进行签名。

(当然这假设您的实施支持long long;我认为它确实存在,因为原始问题使用LL;否则,您可以将UL用于long

答案 1 :(得分:2)

不在当前版本的C ++中。 C ++ 0x将提供强类型枚举。

目前,您可以使用if ( static_cast<size_t>(t) < x )删除警告。

答案 2 :(得分:2)

如果要比较运算符,也可以重载运算符

enum EEE {
    X1 = 1
};

bool operator<(EEE e, std::size_t u) {
  return (int)e < (int)u;
}

但是你必须在右侧为任何整数类型跳舞。否则,如果你执行e < 2,它将是不明确的:编译器可以使用与左侧完全匹配但在右侧需要转换的operator<或其内置运算符,需要促销左侧并严格匹配rigth侧。

所以最终,我会提出以下版本:

/* everything "shorter" than "int" uses either int or unsigned */
bool operator<(EEE e, int u) {
  return (int)e < (int)u;
}

bool operator<(EEE e, unsigned u) {
  return (unsigned int)e < (unsigned int)u;
}


bool operator<(EEE e, long u) {
  return (long)e < (long)u;
}

bool operator<(EEE e, unsigned long u) {
  return (unsigned long)e < (unsigned long)u;
}

/* long long if your compiler has it, too */

不是很好:)但至少你的枚举用户很容易。但是,如果你最终不想与普通的int进行比较,而是针对一些有意义的值,我会做其他人提出的建议,并添加另一个值为2的枚举器,并命名它。这样,警告也会消失。

答案 3 :(得分:1)

根据Are C++ enums signed or unsigned? 你的编译器可以选择是否签名枚举,虽然有一些评论说在C ++ 0x中你可以指定它是无符号的。

答案 4 :(得分:1)

C++ Enumeration Declarations on MSDN

enum EEE : unsigned {
    X1 = 1 
}; 

答案 5 :(得分:0)

为什么不

enum EEE {
    X1 = 1,
    x = 2 // pick more descriptive name, a'course
};

if ( size_t( t ) < x )