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
}
Clang 接受上面的代码但是 gcc 7.2.0 编译错误如下:
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
仅当我通过中间基访问值“i”时,它才不是 constexpr。 哪个编译器是正确的?
最佳答案
从基类到派生类的
static_cast
是 UB,非标准布局类(具有虚拟或非公共(public)成员或基类的类)之间的 static_cast
也是如此或多重继承)。所以要使上面的代码定义明确你需要公共(public)继承
struct base : public root{};
struct derive : public base{};
而且你只能static_cast
从derive
到base
或root
,从base
到 root
,而不是另一个方向。
鉴于 GCC 通常的语义,它可能“应该”接受您的代码,但它不接受也是有道理的,因为它依赖于非标准行为。
关于c++ - 它是 constexpr 从中间派生类引用访问基类成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059745/