【问题标题】:Is there any difference between enum : int and enum : const intenum : int 和 enum : const int 之间有什么区别吗
【发布时间】:2018-01-06 09:28:30
【问题描述】:

我刚刚发现 gcc 和 clang++ 可以让我使用 const int 作为枚举的基础类型。我想知道这是否有任何效用 if 对于所有目的它与基于int 的枚举相同。

我认为这可能会使枚举实例不可分配,但事实并非如此。 (老实说,我认为它不会以与您无法从 const 基类型class C2 : const C1{} 派生的类相同的方式编译)

enum : intenum : const int 之间有什么用处或细微差别吗? 如果没有,为什么编译器会允许?

例子:

#include<iostream>
enum A : const int{ // is this the same as enum A : int ?
   no = 0,
   si
};

int main(){ 
   A a; 
   a = si; // is asignable
   a = no; // twice
   std::cout << (int)a << std::endl; // prints '0'
   return 0;
}

有趣的是,我也能做到这一点enum A : volatile int。 (幸运的是,我不能这样做enum A : int&amp;enum A : int*。)

【问题讨论】:

  • 如果const 将被忽略,我认为它允许const 的唯一原因是支持泛型编程——所以如果有一个包含这样的枚举类的模板类型,即使模板参数是const,它也会起作用。但是程序员也可以很容易地写std::remove_const_t,所以没有太大区别......

标签: c++11 enums constants


【解决方案1】:

为完整起见,以下是相关标准引用(从 C++11 到最新草案):

[dcl.enum]#2 枚举类型 [...] enum-base 的 type-specifier-seq 应命名为整数类型; 忽略任何 cv 限定

其中type-specifier-seq是对应文法产生式中的底层类型规范。

【讨论】:

    【解决方案2】:

    似乎没有区别 - 两者的底层类型都是 int。这里有一些示例测试程序:

    #include <iostream>
    #include <type_traits>
    
    enum e1 : int {};
    enum e2: const int {};
    
    int main() {
        bool e1_type = std::is_same<
            const int
           ,typename std::underlying_type<e1>::type
        >::value; 
    
        bool e2_type = std::is_same<
            const int
           ,typename std::underlying_type<e2>::type
        >::value;
    
        std::cout
        << "underlying type for 'e1' is " << (e1_type?"const":"non-const") << '\n'
        << "underlying type for 'e2' is " << (e2_type?"const":"non-const") << '\n';
    }
    

    https://wandbox.org/permlink/dXLDe80zKhSxglcl

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2010-11-18
      • 2017-01-30
      • 1970-01-01
      相关资源
      最近更新 更多