gpt4 book ai didi

c++ - virtual constexpr 函数如何实现?

转载 作者:太空狗 更新时间:2023-10-29 23:32:03 26 4
gpt4 key购买 nike

从 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 虚函数只有在编译器已知类型时才会在编译时调用,显然它们不会通过虚拟分派(dispatch)调用。

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.

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

关于c++ - virtual constexpr 函数如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com