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 ?

+15
c ++ c ++ 11 virtual-functions constexpr
source share
2 answers

This answer is no longer correct with C ++ 20.

Not. From [dcl.constexpr] / 3 (7.1.5, " constexpr "):

The definition of the constexpr function must satisfy the following requirements:

- it should not be virtual

+27
source share

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 .

+6
source share

All Articles