2016-07-27 13 views
1

それはシャアしかし列挙型基になる型は

enum class Status:char{one=126,two=127,three=128}; 
Status s = Status::three; 

「基になる型に対して大きすぎる列挙値「私は次のコマンドを実行した場合のコードコンパイラがないことを私にエラーを与えるだろう私にすべてのエラーを与え、静かに文字の上部範囲は

char x = 128; 

を越えているので、コンパイラは、通常のデータ型の場合をチェックインし、列挙型基になる型の場合に範囲をチェックしません、なぜ特定の理由があることを無視します。

+0

を行うことができます。このように、あなたが行うことはできません。これが許されなければ、 'getchar()'や 'istream :: get()'のようなAPIの返された 'int'を' char'に変換するのは面倒かもしれません。 – neuront

+0

あなたの実装では 'char'のように見えます。その値はおそらく-128から127の範囲です。128は 'char'をオーバーフローしますが、不正な形式ではありません。署名付きオーバーフローは未定義の動作であることに注意してください。私はそれが不定値で定数を持っていることは醜いと思う。 – KABoissonneault

+0

どのコンパイラを使用していますか? gcc-6.1は 'error:enumerator value 128は基底型 'char''の範囲外です。 – Tim

答えて

2

C++ 11では、「変換の絞り込み」とその許可と禁止の制限が導入されました。 5.19§3には、「変換された定数式」を記述し、変換を狭めることを特に除外し、そのような式が列挙子の初期化子で使用されることに注意する節があります。

enum class Foo : char { one = 128 }; 
unsigned char uc1 = {-1}; 

をしかし、あなたは私が推測する下位互換性のために

enum class Foo : char { one = (char)128 }; 
unsigned char uc1 = -1; 

5.19 [expr.const]§3

[...] A converted constant expression of type T is an expression, implicitly converted to a prvalue of type T, where the converted expression is a core constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-torvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4). [ Note: such expressions may be used in new expressions (5.3.4), as case expressions (6.4.2), as enumerator initializers if the underlying type is fixed (7.2), as array bounds (8.3.4), and as integral or enumeration non-type template arguments (14.3). —end note ]