简体   繁体   English

虚函数可以是constexpr吗?

[英]Can virtual functions be constexpr?

Can virtual functions like X::f() in the following code可以在下面的代码中使用像X::f()这样的虚函数吗

struct X 
{
    constexpr virtual int f() const 
    {
        return 0;
    }
};

be constexpr ?constexpr吗?

This answer is no longer correct as of C++20.从 C++20 开始,这个答案不再正确。

No. From [dcl.constexpr]/3 (7.1.5, "The constexpr specifier"):编号来自 [dcl.constexpr]/3(7.1.5,“ constexpr说明符”):

The definition of a constexpr function shall satisfy the following requirements: constexpr函数的定义应满足以下要求:

— it shall not be virtual — 它不应是虚拟的

Up through C++17, virtual functions could not be declared constexpr .在 C++17 之前, virtual函数不能声明为constexpr The general reason being that, in constexpr code, everything happen can at compile time.一般原因是,在constexpr代码中,一切都可以在编译时发生。 So there really isn't much point to having a function which takes a reference to a base class and calls virtual functions on it;因此,拥有一个引用基类并在其上调用virtual函数的函数确实没有多大意义; you may as well make it a template function and pass the real type, since you know the real type.您不妨将其设为template函数并传递真实类型,因为您知道真实类型。

Of course, this thinking doesn't really work as constexpr code becomes more complex, or if you want to share interfaces between compile-time and runtime code.当然,随着constexpr代码变得更加复杂,或者如果您想在编译时代码和运行时代码之间共享接口,这种想法实际上并不奏效。 In both cases, losing track of the original type is easy to do.在这两种情况下,很容易忘记原始类型。 It would also allow std::error_code to be more constexpr -friendly.它还将允许std::error_codeconstexpr更加友好。

Also, the fact that C++20 will allow us to do (limited) dynamic allocation of objects means that it is very easy to lose track of the original type.此外,C++20 将允许我们进行(有限的)对象动态分配这一事实意味着很容易忘记原始类型。 You can now create a vector<Base*> in constexpr code, insert some Derived class instances into it, and pass that to a constexpr function to operate on.您现在可以在constexpr代码中创建一个vector<Base*> ,将一些Derived类实例插入其中,并将其传递给constexpr函数进行操作。

So C++20 allows virtual functions to be declared constexpr .所以 C++20 允许将virtual函数声明为constexpr

Can virtual functions be constexpr?虚函数可以是constexpr吗?

Yes.是的。 Only since C++20 , virtual functions can be constexpr .只有从 C++20 开始,虚函数才可以是constexpr

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

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