我刚刚发现gcc和clang++可以让我对枚举的底层类型使用const int
。我想知道这是否有任何效用,如果出于所有目的,它与拥有基于 int
的枚举相同.
我以为这可能是它会使枚举实例不可分配,但事实并非如此。(老实说,我认为它不会以与无法从 const 基类型派生的类相同的方式进行编译class C2 : const C1{}
enum : int
和enum : 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&
或enum A : int*
这样做。
为了完整起见,以下是相关的标准报价(从 C++11 到最新草案(:
[dcl.enum]#2 枚举类型 [...]枚举基的类型说明符序列应命名一个整型类型;任何简历资格都将被忽略。
其中,类型说明符-seq 是相应语法生产中的基础类型规范。
似乎没有区别 - 两者的底层类型都是 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