简体   繁体   English

虚拟constexpr功能如何可能?

[英]How are virtual constexpr function possible?

As of C++2a, virtual functions can now be constexpr. 从C ++ 2a开始,虚函数现在可以是constexpr。 But as far as I know, you still cannot call arbitrary function pointers in constexpr context. 但据我所知,你仍然无法在constexpr上下文中调用任意函数指针。

Dynamic polymorphism is usually implemented using a vtable, which contains the function pointer to call. 动态多态通常使用vtable实现,其中包含要调用的函数指针。

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. 此外,使用virtual动态多态性可用于调用类型的覆盖函数,这些函数在编译时不知道它是哪一个。 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? 因此,考虑到那些在编译时无法调用函数指针的函数,并且当编译器没有足够的信息来静态推断调用哪个函数时,会使用虚拟多态,虚拟constexpr函数如何可能?

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. 请记住,只有当编译器已经知道类型时才会在编译时调用constexpr虚函数,显然它们不会通过虚拟调度调用。

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. 它也有一个非常好的激励例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM