2015-09-17 23 views
6
#include <iostream> 

union gc_bits { 
    size_t value; 
    struct { 
     size_t arena : 2; 
    } bits; 

    constexpr gc_bits(size_t value_) : value(value_) { 
    } 
}; 

static constexpr size_t get_max_arenas() { 
    return gc_bits(~0ULL).bits.arena; 
} 

size_t current_colour[get_max_arenas()]; // error 

int main() { 
    std::cout << get_max_arenas() << std::endl; 
} 

get_max_arenasはconstexprではないため、配列の宣言に誤りがあります。なぜそうでなければならないのかはっきりしない。少しあなたのプログラム言い換えなぜこれはconstexprではありませんか?

+2

ところで、あなたはの[値]に書き込み、その後、労働組合でbits' 'から読み取ります。それはC++の未定義の動作ではありませんか? – gurka

+0

私は、あなたがユニオンの共通接頭辞から読むことが許されていること、そして値とビットの両方がsize_tで始まっているので、それが許されるべきだと思います。 – DrPizza

+0

ところで2:標準では、2つのビットがsize_tの左端か右端かどうかは分かりません。移植性を制限します。私はシフトとマスクを試してみる。 –

答えて

7

static constexpr auto gma = get_max_arenas(); 

size_t current_colour[gma]; // error 

はクランエラーを与える:

read of member 'bits' of union with active member 'value' is not allowed in a constant expression

このエラーが発生した理由は、コンストラクタがvalueを設定していることで、その後、あなたがbitsを読み取ろう。これは、@ gurkaによってコメントされているように許可されていません。

Standard引用:

[expr.const]

2 A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

(2.8) — an lvalue-to-rvalue conversion (4.1) or modification (5.18, 5.2.6, 5.3.2) that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof;

+1

ああ、ちょうど任意かつ無意味な制限。ありがとう。 – DrPizza

+0

@DrPizzaいいえ、それは恣意的ではありません:実行時には、非アクティブな共用体メンバにアクセスするための[未定義の動作](http://stackoverflow.com/q/11373203/819272)コンパイラエラーの余分なサービスがあります。 – TemplateRex

+0

あなたがそれが恣意的ではないと思うなら、些細なコンストラクタを持つ型の型打ちを許さないという理論的根拠を説明してください。あなたの答えは、C11がなぜこのようなことを許すのが間違っているのかを必ず記述してください。 – DrPizza

関連する問題