-
C++20 allows virtual functions to be declared
constexprstruct Base { virtual ~Base() noexcept = default; virtual int foo() const noexcept = 0; }; struct Derived : public Base { constexpr int foo() const noexcept override { return 2; }; }; int main() { { constexpr Derived derived; constexpr auto value = derived.foo(); static_assert(value == 2); } { std::unique_ptr<Base> base = std::make_unique<Derived>(); const auto value = base->foo(); } }
Note: A
constexprvirtual function can override a non-constexprfunction and vice versa. -
string,string_view,vector, andtupleare nowconstexpras well assort,all_of, ... algorithms -
Use
dynamic_castandtypeid -
Do dynamic memory allocations and deallocations
-
Change the active member of a
union -
Contain
try/catchblocks-
But
throwstatements are still not allowed -
try/catchblocks are no-ops when evaluated in a constant expression
-
consteval declares immediate functions that must produce a compile time constant expression,
a non-constant result should be a compilation error.
consteval auto Square(int number) {
return number * number;
}
auto number = 10;
auto value = Square(number); // error: the value of 'number' is not usable in a constant expression
const auto number = 10;
auto value = Square(number); // ok: everything is constant
constexpr auto number = 10;
constexpr auto value = Square(number); // ok📎 As a comparison, constexpr function may be evaluated at compile time and runtime, and need not produce a constant in all cases.