Bartłomiej Filipek, 29th September 2022, cppstories.com
20 Smaller yet Handy
C++20Features
Part 1 - language
About Me
•Author of cppstories.com•~15y professional coding experience•4x Microsoft MVP, since 2018•C++ ISO Member•@Xara.com since 2014oMostly text related features for advanced document editors•Somehow addicted to C++
5. Class-types in non-type template parameters (NTTP)
9
•Before C++20, for a non type template parameter, you could use:olvalue reference type (to object or to function);oan integral type;oa pointer type (to object or to function);oa pointer to member type (to member object or to member function);oan enumeration type;•But since C++20, we can now add:ostructures and simple classes - structural typesofloating-point numbersolambdas
•Here are the main rules of this feature:oOnly for aggregate types and for non-static data membersoThey have to have the same order of data members in a class declaration (not in C)oNot all data members must be specified in the expressionoYou cannot mix regular initialization with designersoThere can only be one designator for a data memberoYou cannot nest designators.
8. Nodiscard Attribute Improvements
12
[[nodiscard(“Don’t call this heavy function if you don’t need the result!”)]] bool Compute();try: https://godbolt.org/z/16Kzbse8z
What’s more thanks to P0600 this attribute is now applied in many places in the Standard Library, for example:
void print(const std::ranges::range auto& container) {for (std::size_t i = 0; constauto& x : container) { std::cout << i << “ -> “ << x << ‘\n’;// or std::cout << std::format(“{} -> {}”, i, x); ++i; }}
// undefined behavior if foo() returns by valuefor (auto& x : foo().items()) { /* .. */ } // fine:for (T thing = foo(); auto& x : thing.items()) { /* … */ }
10. New keyword consteval - immediate functions
14
constevalint sum(int a, int b) { return a + b; }constexprint sum_c(int a, int b) { return a + b; }int main() {constexprauto c = sum(100, 100);static_assert(c == 200);constexprauto val = 10;static_assert(sum(val, val) == 2*val);int a = 10;int b = sum_c(a, 10); // fine with constexpr function// int d = sum(a, 10); // error! the value of 'a' is // not usable in a constant expression}