struct root
{
int i = 0;
};
struct base: root{};
struct derive: base{};
constexpr derive d0;
int main()
{
constexpr auto& r = static_cast<root const&>(d0);
constexpr auto& b = static_cast<base const&>(r);
constexpr auto& d = static_cast<derive const&>(r);
static_assert(d0.i == 0, ""); // ok
static_assert(r.i == 0, ""); // ok
static_assert(b.i == 0, ""); // error in gcc
static_assert(d.i == 0, ""); // ok
}
クラン下にエラーでコンパイル上記のコードが、GCC 7.2.0を受け入れる:値にアクセスする場合にのみ、「i」は、中間ベースを介しconstexprのされていない中間抽象クラス参照から基本クラスメンバにアクセスするconstexprですか?
prog.cc:17:5: error: non-constant condition for static assertion
static_assert(b.i == 0, "");
^~~~~~~~~~~~~
prog.cc:17:5: error: accessing value of 'd.derive::<anonymous>.base::<anonymous>' through a 'const base'
glvalue in a constant
。 どのコンパイラが正しいですか?
コンパイルするC++の仕様は何ですか? C++ 17? – dlasalle
は、C++ 14とC++ 17の両方でコンパイルされても同じ結果を示します。 – kwanti
興味深い使用例です。私はそれがおそらくgccによって許可されるべきだと思うという点でチャイムしたいと思いますが、おそらく彼らはそれが安全でないと保証しなかったかもしれません。 (ダウンキャストのための 'dynamic_cast'のみ) – AndyG