C++ constexpr 最终虚函数

问题描述

我正在 C++ 派生类中实现纯虚函数,并标记方法 final。我还想标记函数 constexpr,但似乎标准不允许这样做。

编译器难以实现这一点是否有任何实际原因?还是因为通常的“这个功能被认为不够重要而无法添加到标准”的想法而忽略了这样一个功能

根据评论,我最初的问题似乎没有说明我在询问 constexpr final 函数。以下代码说明了我要编译的内容

struct A {
    virtual int foo() const;
};

struct B : public A {
    // Note that this function is final,and is therefore no longer
    // polymorphic in types derived from B (e.g.,the function call
    // no longer requires a lookup in the virtual method table
    // when the compile-time type is kNown to be derived from B)
    constexpr int foo() const final {
        return 0;
    }
};

请注意,这被标记Can virtual functions be constexpr? 的副本,因为在 C++20 中,无论是否使用 final 关键字都可以编译上述代码

解决方法