Gui*_*cot 2 c++ virtual-functions function-pointers constexpr c++20
从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{});
}
Run Code Online (Sandbox Code Playgroud)
因此,考虑到那些在编译时无法调用函数指针并且在编译器没有足够的信息来静态地推断要调用的函数时使用了虚拟多态性的方法,虚拟constexpr函数怎么可能?