Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are virtual constexpr function possible?

As of C++2a, virtual functions can now be constexpr. But as far as I know, you still cannot call arbitrary function pointers in constexpr context.

Dynamic polymorphism is usually implemented using a vtable, which contains the function pointer to call.

Also, dynamic polymorphism with virtual is useful to call overriding functions of a type you don't know which one it is at compile time. For example:

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{});
}

So considering those that function pointers cannot be called at compile time and virtual polymorphism is used when the compiler don't have enough information to statically infer what function to call, how are virtual constexpr functions possible?

like image 785
Guillaume Racicot Avatar asked Oct 31 '25 06:10

Guillaume Racicot


1 Answers

Please keep in mind that constexpr virtual functions would be called at compile time only when the type is already known to the compiler and obviously they would not be called through virtual dispatch.

Corresponding proposal provides similar explanation:

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.

It also has a very nice motivating example.

like image 63
SergeyA Avatar answered Nov 01 '25 21:11

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!