很简单。为什么会这样?它适用于所有其他整数类型。
enum : unsigned short {
ushort_min = static_cast<unsigned short>(0u),
ushort_max = static_cast<unsigned short>(~0u)
};
enum : short {
short_min = short(ushort_max << (sizeof(short) * char_bit - 1)),
short_max = short(ushort_max >> 1)
};
std::cout << short_min; // BOOM
示例代码使用 gcc 编译没有错误。这里的答案可能是“升级你的编译器”:
$ cat t.C
#include <iostream>
enum : unsigned short {
ushort_min = static_cast<unsigned short>(0u),
ushort_max = static_cast<unsigned short>(~0u)
};
enum : short {
short_min = short(ushort_max << (sizeof(short) * 8 - 1)),
short_max = short(ushort_max >> 1)
};
int main()
{
std::cout << short_min; // BOOM
}
$ g++ -std=c++14 -c -o t.o t.C
$ g++ --version
g++ (GCC) 5.3.1 20151207 (Red Hat 5.3.1-2)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.