c++c++11virtual-functionsconstexpr

Can virtual functions be constexpr?


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

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

be constexpr?


Solution

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