代码之家  ›  专栏  ›  技术社区  ›  Kirill V. Lyadvinsky

有没有办法使“enum”类型不带符号?

  •  10
  • Kirill V. Lyadvinsky  · 技术社区  · 16 年前

    有没有办法 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 回复  |  直到 16 年前
        1
  •  8
  •   James McNellis    16 年前

    您可以尝试:

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

    U ,整数文本是有符号的。

    (当然,这假设您的实现支持 long long ; 我想是的,因为原来的问题 LL ; 否则,您可以使用 UL long ).

        2
  •  2
  •   In silico    16 年前

    就目前而言,你可以使用 if ( static_cast<size_t>(t) < x )

        3
  •  2
  •   Johannes Schaub - litb    16 年前

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

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

    但是你必须为右边的任何整数类型跳这个舞。否则如果你这么做了 e < 2 这是不明确的:编译器可以使用 operator<

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

    /* 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 ,并命名它。这样,警告也会消失。

        4
  •  1
  •   Community Mohan Dere    9 年前
        5
  •  1
  •   Gilles 'SO- stop being evil'    13 年前

    C++ Enumeration Declarations on MSDN :

    enum EEE : unsigned {
        X1 = 1 
    }; 
    
        6
  •  0
  •   Potatoswatter    16 年前

    为什么不呢?

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

    或

    if ( size_t( t ) < x )