Can virtual functions like X::f()
in the following code
struct X { constexpr virtual int f() const { return 0; } };
be constexpr
?
Can virtual functions be constexpr? Yes. Only since C++20, virtual functions can be constexpr .
A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type.
We allow annotating a function parameter with constexpr with the same meaning as a variable declaration: must be initialized with a constant expression. We add a new keyword, maybe_constexpr , that deduces whether the parameter is known at compile time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With