c++ - 它是 constexpr 从中间派生类引用访问基类成员吗?

标签 c++ constexpr

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_castderivebaseroot,从baseroot,而不是另一个方向。

鉴于 GCC 通常的语义,它可能“应该”接受您的代码,但它不接受也是有道理的,因为它依赖于非标准行为。

关于c++ - 它是 constexpr 从中间派生类引用访问基类成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059745/

相关文章:

java - 为什么Java平台独立?

c++ - 两平方和分解计数

c++ - 如何检查 const 数组成员在编译时是否单调增长

c++ - 如何在 C++ 中定义每个维度都是不同类型的 3d 数组?

带模板的 C++ 数据包生成器

c++ - std::string 最终会成为我们的编译时字符串吗?

c++ - 在结构中初始化静态 constexpr 变量和类

c++ - 数组初始化编译时间 - Constexpr 序列

c++ - 为什么 const double && 不适用于左值引用?

c++ - 通过索引实现 'constexpr for'