Prior to C ++ 17, virtual functions could not be declared constexpr . The common reason is that in constexpr code everything can happen at compile time. So in reality, it makes little sense to have a function that takes a reference to the base class and calls virtual functions for it; you can also make it a template function and pass the real type, since you know the real type.
Of course, this thinking does not work, as constexpr code becomes more complex, or if you want to separate interfaces between compilation code and runtime. In both cases, losing the original track is easy. It would also allow std::error_code be larger than constexpr -friendly.
In addition, the fact that C ++ 20 will allow us to perform (limited) dynamic allocation of objects means that it is very easy to lose track of the original type. Now you can create a vector<Base*> in constexpr code, insert several instances of the Derived class into it, and pass it to the constexpr function to work.
Therefore, C ++ 20 allows you to declare virtual constexpr functions .
Nicol bolas
source share