virtual constexpr 函数如何实现?

How are virtual constexpr function possible?

从 C++2a 开始,虚函数现在可以是 constexpr。但据我所知,你仍然不能在 constexpr 上下文中调用任意函数指针。

动态多态通常使用一个vtable来实现,其中包含要调用的函数指针。

此外,virtual 的动态多态性对于调用您在编译时不知道它是哪种类型的重写函数很有用。例如:

struct A {
    virtual void fn() const {
        std::cout << 'A' << std::endl;
    }
};

void a_or_b(A const& a) {
    // The compiler has no idea `B` exists
    // it must be deferred at runtime
    a.fn();
}

struct B : A {
    void fn() const override {
        std::cout << 'A' << std::endl;
    }
};

int main() {
    // We choose which class is sent
    a_or_b(rand() % 2 ? A{} : B{});
}

所以考虑到那些在编译时不能调用函数指针并且当编译器没有足够的信息来静态推断要调用什么函数时使用虚拟多态性,虚拟 constexpr 函数如何可能?

请记住 constexpr 虚函数只有在编译器已知类型时才会在编译时调用,显然它们不会通过虚拟分派调用。

Corresponding proposal 提供类似的解释:

Virtual function calls are currently prohibited in constant expressions. Since in a constant expression the dynamic type of the object is required to be known (in order to, for example, diagnose undefined behavior in casts), the restriction is unnecessary and artificial. We propose the restriction be removed.

它还有一个很好的激励示例。