Reputation: 41780
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?
Upvotes: 4
Views: 1240
Reputation: 62583
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.
Upvotes: 14