Can virtual functions be constexpr?

后端 未结 3 1790
旧巷少年郎
旧巷少年郎 2021-02-13 02:46

Can virtual functions like X::f() in the following code

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

相关标签:
3条回答
  • 2021-02-13 03:00

    This answer is no longer correct as of C++20.

    No. From [dcl.constexpr]/3 (7.1.5, "The constexpr specifier"):

    The definition of a constexpr function shall satisfy the following requirements:

    — it shall not be virtual

    0 讨论(0)
  • 2021-02-13 03:19

    Up through C++17, virtual functions could not be declared constexpr. The general reason being that, in constexpr code, everything happen can at compile time. 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; you may as well make it a template function and pass the real type, since you know the real type.

    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. 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.

    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. 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.

    So C++20 allows virtual functions to be declared constexpr.

    0 讨论(0)
  • 2021-02-13 03:24

    Can virtual functions be constexpr?

    Yes. Only since C++20, virtual functions can be constexpr.

    0 讨论(0)
提交回复
热议问题