{"id":13400233,"url":"https://github.com/AnthonyCalandra/modern-cpp-features","last_synced_at":"2025-03-14T06:31:36.183Z","repository":{"id":37334223,"uuid":"72396492","full_name":"AnthonyCalandra/modern-cpp-features","owner":"AnthonyCalandra","description":"A cheatsheet of modern C++ language and library features.","archived":false,"fork":false,"pushed_at":"2024-10-15T01:22:04.000Z","size":226,"stargazers_count":19671,"open_issues_count":4,"forks_count":2092,"subscribers_count":790,"default_branch":"master","last_synced_at":"2024-10-29T11:13:11.036Z","etag":null,"topics":["cpp","cpp11","cpp14","cpp17","cpp20"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AnthonyCalandra.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-10-31T03:34:22.000Z","updated_at":"2024-10-29T09:45:59.000Z","dependencies_parsed_at":"2024-01-03T04:01:14.773Z","dependency_job_id":"a2b7d2c0-68ae-40f8-9a4c-34acbefcdb4b","html_url":"https://github.com/AnthonyCalandra/modern-cpp-features","commit_stats":{"total_commits":158,"total_committers":38,"mean_commits":4.157894736842105,"dds":0.3481012658227848,"last_synced_commit":"65d08b8d53859fdd880e341d00124693becb0074"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AnthonyCalandra%2Fmodern-cpp-features","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AnthonyCalandra%2Fmodern-cpp-features/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AnthonyCalandra%2Fmodern-cpp-features/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AnthonyCalandra%2Fmodern-cpp-features/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AnthonyCalandra","download_url":"https://codeload.github.com/AnthonyCalandra/modern-cpp-features/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243537625,"owners_count":20307098,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","cpp11","cpp14","cpp17","cpp20"],"created_at":"2024-07-30T19:00:49.797Z","updated_at":"2025-03-14T06:31:35.880Z","avatar_url":"https://github.com/AnthonyCalandra.png","language":null,"readme":"# C++20/17/14/11\n\n## Overview\n\nC++20 includes the following new language features:\n- [coroutines](#coroutines)\n- [concepts](#concepts)\n- [three-way comparison](#three-way-comparison)\n- [designated initializers](#designated-initializers)\n- [template syntax for lambdas](#template-syntax-for-lambdas)\n- [range-based for loop with initializer](#range-based-for-loop-with-initializer)\n- [\\[\\[likely\\]\\] and \\[\\[unlikely\\]\\] attributes](#likely-and-unlikely-attributes)\n- [deprecate implicit capture of this](#deprecate-implicit-capture-of-this)\n- [class types in non-type template parameters](#class-types-in-non-type-template-parameters)\n- [constexpr virtual functions](#constexpr-virtual-functions)\n- [explicit(bool)](#explicitbool)\n- [immediate functions](#immediate-functions)\n- [using enum](#using-enum)\n- [lambda capture of parameter pack](#lambda-capture-of-parameter-pack)\n- [char8_t](#char8_t)\n- [constinit](#constinit)\n- [\\_\\_VA\\_OPT\\_\\_](#__VA_OPT__)\n\nC++20 includes the following new library features:\n- [concepts library](#concepts-library)\n- [formatting library](#formatting-library)\n- [synchronized buffered outputstream](#synchronized-buffered-outputstream)\n- [std::span](#stdspan)\n- [bit operations](#bit-operations)\n- [math constants](#math-constants)\n- [std::is_constant_evaluated](#stdis_constant_evaluated)\n- [std::make_shared supports arrays](#stdmake_shared-supports-arrays)\n- [starts_with and ends_with on strings](#starts_with-and-ends_with-on-strings)\n- [check if associative container has element](#check-if-associative-container-has-element)\n- [std::bit_cast](#stdbit_cast)\n- [std::midpoint](#stdmidpoint)\n- [std::to_array](#stdto_array)\n- [std::bind_front](#stdbind_front)\n- [uniform container erasure](#uniform-container-erasure)\n- [three-way comparison helpers](#three-way-comparison-helpers)\n- [std::lexicographical_compare_three_way](#stdlexicographical_compare_three_way)\n\nC++17 includes the following new language features:\n- [template argument deduction for class templates](#template-argument-deduction-for-class-templates)\n- [declaring non-type template parameters with auto](#declaring-non-type-template-parameters-with-auto)\n- [folding expressions](#folding-expressions)\n- [new rules for auto deduction from braced-init-list](#new-rules-for-auto-deduction-from-braced-init-list)\n- [constexpr lambda](#constexpr-lambda)\n- [lambda capture this by value](#lambda-capture-this-by-value)\n- [inline variables](#inline-variables)\n- [nested namespaces](#nested-namespaces)\n- [structured bindings](#structured-bindings)\n- [selection statements with initializer](#selection-statements-with-initializer)\n- [constexpr if](#constexpr-if)\n- [utf-8 character literals](#utf-8-character-literals)\n- [direct-list-initialization of enums](#direct-list-initialization-of-enums)\n- [\\[\\[fallthrough\\]\\], \\[\\[nodiscard\\]\\], \\[\\[maybe_unused\\]\\] attributes](#fallthrough-nodiscard-maybe_unused-attributes)\n- [\\_\\_has\\_include](#\\_\\_has\\_include)\n- [class template argument deduction](#class-template-argument-deduction)\n\nC++17 includes the following new library features:\n- [std::variant](#stdvariant)\n- [std::optional](#stdoptional)\n- [std::any](#stdany)\n- [std::string_view](#stdstring_view)\n- [std::invoke](#stdinvoke)\n- [std::apply](#stdapply)\n- [std::filesystem](#stdfilesystem)\n- [std::byte](#stdbyte)\n- [splicing for maps and sets](#splicing-for-maps-and-sets)\n- [parallel algorithms](#parallel-algorithms)\n- [std::sample](#stdsample)\n- [std::clamp](#stdclamp)\n- [std::reduce](#stdreduce)\n- [prefix sum algorithms](#prefix-sum-algorithms)\n- [gcd and lcm](#gcd-and-lcm)\n- [std::not_fn](#stdnot_fn)\n- [string conversion to/from numbers](#string-conversion-tofrom-numbers)\n- [rounding functions for chrono durations and timepoints](#rounding-functions-for-chrono-durations-and-timepoints)\n\nC++14 includes the following new language features:\n- [binary literals](#binary-literals)\n- [generic lambda expressions](#generic-lambda-expressions)\n- [lambda capture initializers](#lambda-capture-initializers)\n- [return type deduction](#return-type-deduction)\n- [decltype(auto)](#decltypeauto)\n- [relaxing constraints on constexpr functions](#relaxing-constraints-on-constexpr-functions)\n- [variable templates](#variable-templates)\n- [\\[\\[deprecated\\]\\] attribute](#deprecated-attribute)\n\nC++14 includes the following new library features:\n- [user-defined literals for standard library types](#user-defined-literals-for-standard-library-types)\n- [compile-time integer sequences](#compile-time-integer-sequences)\n- [std::make_unique](#stdmake_unique)\n\nC++11 includes the following new language features:\n- [move semantics](#move-semantics)\n- [variadic templates](#variadic-templates)\n- [rvalue references](#rvalue-references)\n- [forwarding references](#forwarding-references)\n- [initializer lists](#initializer-lists)\n- [static assertions](#static-assertions)\n- [auto](#auto)\n- [lambda expressions](#lambda-expressions)\n- [decltype](#decltype)\n- [type aliases](#type-aliases)\n- [nullptr](#nullptr)\n- [strongly-typed enums](#strongly-typed-enums)\n- [attributes](#attributes)\n- [constexpr](#constexpr)\n- [delegating constructors](#delegating-constructors)\n- [user-defined literals](#user-defined-literals)\n- [explicit virtual overrides](#explicit-virtual-overrides)\n- [final specifier](#final-specifier)\n- [default functions](#default-functions)\n- [deleted functions](#deleted-functions)\n- [range-based for loops](#range-based-for-loops)\n- [special member functions for move semantics](#special-member-functions-for-move-semantics)\n- [converting constructors](#converting-constructors)\n- [explicit conversion functions](#explicit-conversion-functions)\n- [inline-namespaces](#inline-namespaces)\n- [non-static data member initializers](#non-static-data-member-initializers)\n- [right angle brackets](#right-angle-brackets)\n- [ref-qualified member functions](#ref-qualified-member-functions)\n- [trailing return types](#trailing-return-types)\n- [noexcept specifier](#noexcept-specifier)\n- [char32_t and char16_t](#char32_t-and-char16_t)\n- [raw string literals](#raw-string-literals)\n\nC++11 includes the following new library features:\n- [std::move](#stdmove)\n- [std::forward](#stdforward)\n- [std::thread](#stdthread)\n- [std::to_string](#stdto_string)\n- [type traits](#type-traits)\n- [smart pointers](#smart-pointers)\n- [std::chrono](#stdchrono)\n- [tuples](#tuples)\n- [std::tie](#stdtie)\n- [std::array](#stdarray)\n- [unordered containers](#unordered-containers)\n- [std::make_shared](#stdmake_shared)\n- [std::ref](#stdref)\n- [memory model](#memory-model)\n- [std::async](#stdasync)\n- [std::begin/end](#stdbeginend)\n\n## C++20 Language Features\n\n### Coroutines\n\n\u003e **Note:** While these examples illustrate how to use coroutines at a basic level, there is lots more going on when the code is compiled. These examples are not meant to be complete coverage of C++20's coroutines. Since the `generator` and `task` classes are not provided by the standard library yet, I used the cppcoro library to compile these examples.\n\n_Coroutines_ are special functions that can have their execution suspended and resumed. To define a coroutine, the `co_return`, `co_await`, or `co_yield` keywords must be present in the function's body. C++20's coroutines are stackless; unless optimized out by the compiler, their state is allocated on the heap.\n\nAn example of a coroutine is a _generator_ function, which yields (i.e. generates) a value at each invocation:\n```c++\ngenerator\u003cint\u003e range(int start, int end) {\n  while (start \u003c end) {\n    co_yield start;\n    start++;\n  }\n\n  // Implicit co_return at the end of this function:\n  // co_return;\n}\n\nfor (int n : range(0, 10)) {\n  std::cout \u003c\u003c n \u003c\u003c std::endl;\n}\n```\nThe above `range` generator function generates values starting at `start` until `end` (exclusive), with each iteration step yielding the current value stored in `start`. The generator maintains its state across each invocation of `range` (in this case, the invocation is for each iteration in the for loop). `co_yield` takes the given expression, yields (i.e. returns) its value, and suspends the coroutine at that point. Upon resuming, execution continues after the `co_yield`.\n\nAnother example of a coroutine is a _task_, which is an asynchronous computation that is executed when the task is awaited:\n```c++\ntask\u003cvoid\u003e echo(socket s) {\n  for (;;) {\n    auto data = co_await s.async_read();\n    co_await async_write(s, data);\n  }\n\n  // Implicit co_return at the end of this function:\n  // co_return;\n}\n```\nIn this example, the `co_await` keyword is introduced. This keyword takes an expression and suspends execution if the thing you're awaiting on (in this case, the read or write) is not ready, otherwise you continue execution. (Note that under the hood, `co_yield` uses `co_await`.)\n\nUsing a task to lazily evaluate a value:\n```c++\ntask\u003cint\u003e calculate_meaning_of_life() {\n  co_return 42;\n}\n\nauto meaning_of_life = calculate_meaning_of_life();\n// ...\nco_await meaning_of_life; // == 42\n```\n\n### Concepts\n_Concepts_ are named compile-time predicates which constrain types. They take the following form:\n```\ntemplate \u003c template-parameter-list \u003e\nconcept concept-name = constraint-expression;\n```\nwhere `constraint-expression` evaluates to a constexpr Boolean. _Constraints_ should model semantic requirements, such as whether a type is a numeric or hashable. A compiler error results if a given type does not satisfy the concept it's bound by (i.e. `constraint-expression` returns `false`). Because constraints are evaluated at compile-time, they can provide more meaningful error messages and runtime safety.\n```c++\n// `T` is not limited by any constraints.\ntemplate \u003ctypename T\u003e\nconcept always_satisfied = true;\n// Limit `T` to integrals.\ntemplate \u003ctypename T\u003e\nconcept integral = std::is_integral_v\u003cT\u003e;\n// Limit `T` to both the `integral` constraint and signedness.\ntemplate \u003ctypename T\u003e\nconcept signed_integral = integral\u003cT\u003e \u0026\u0026 std::is_signed_v\u003cT\u003e;\n// Limit `T` to both the `integral` constraint and the negation of the `signed_integral` constraint.\ntemplate \u003ctypename T\u003e\nconcept unsigned_integral = integral\u003cT\u003e \u0026\u0026 !signed_integral\u003cT\u003e;\n```\nThere are a variety of syntactic forms for enforcing concepts:\n```c++\n// Forms for function parameters:\n// `T` is a constrained type template parameter.\ntemplate \u003cmy_concept T\u003e\nvoid f(T v);\n\n// `T` is a constrained type template parameter.\ntemplate \u003ctypename T\u003e\n  requires my_concept\u003cT\u003e\nvoid f(T v);\n\n// `T` is a constrained type template parameter.\ntemplate \u003ctypename T\u003e\nvoid f(T v) requires my_concept\u003cT\u003e;\n\n// `v` is a constrained deduced parameter.\nvoid f(my_concept auto v);\n\n// `v` is a constrained non-type template parameter.\ntemplate \u003cmy_concept auto v\u003e\nvoid g();\n\n// Forms for auto-deduced variables:\n// `foo` is a constrained auto-deduced value.\nmy_concept auto foo = ...;\n\n// Forms for lambdas:\n// `T` is a constrained type template parameter.\nauto f = []\u003cmy_concept T\u003e (T v) {\n  // ...\n};\n// `T` is a constrained type template parameter.\nauto f = []\u003ctypename T\u003e requires my_concept\u003cT\u003e (T v) {\n  // ...\n};\n// `T` is a constrained type template parameter.\nauto f = []\u003ctypename T\u003e (T v) requires my_concept\u003cT\u003e {\n  // ...\n};\n// `v` is a constrained deduced parameter.\nauto f = [](my_concept auto v) {\n  // ...\n};\n// `v` is a constrained non-type template parameter.\nauto g = []\u003cmy_concept auto v\u003e () {\n  // ...\n};\n```\nThe `requires` keyword is used either to start a `requires` clause or a `requires` expression:\n```c++\ntemplate \u003ctypename T\u003e\n  requires my_concept\u003cT\u003e // `requires` clause.\nvoid f(T);\n\ntemplate \u003ctypename T\u003e\nconcept callable = requires (T f) { f(); }; // `requires` expression.\n\ntemplate \u003ctypename T\u003e\n  requires requires (T x) { x + x; } // `requires` clause and expression on same line.\nT add(T a, T b) {\n  return a + b;\n}\n```\nNote that the parameter list in a `requires` expression is optional. Each requirement in a `requires` expression are one of the following:\n\n* **Simple requirements** - asserts that the given expression is valid.\n\n```c++\ntemplate \u003ctypename T\u003e\nconcept callable = requires (T f) { f(); };\n```\n* **Type requirements** - denoted by the `typename` keyword followed by a type name, asserts that the given type name is valid.\n\n```c++\nstruct foo {\n  int foo;\n};\n\nstruct bar {\n  using value = int;\n  value data;\n};\n\nstruct baz {\n  using value = int;\n  value data;\n};\n\n// Using SFINAE, enable if `T` is a `baz`.\ntemplate \u003ctypename T, typename = std::enable_if_t\u003cstd::is_same_v\u003cT, baz\u003e\u003e\u003e\nstruct S {};\n\ntemplate \u003ctypename T\u003e\nusing Ref = T\u0026;\n\ntemplate \u003ctypename T\u003e\nconcept C = requires {\n                     // Requirements on type `T`:\n  typename T::value; // A) has an inner member named `value`\n  typename S\u003cT\u003e;     // B) must have a valid class template specialization for `S`\n  typename Ref\u003cT\u003e;   // C) must be a valid alias template substitution\n};\n\ntemplate \u003cC T\u003e\nvoid g(T a);\n\ng(foo{}); // ERROR: Fails requirement A.\ng(bar{}); // ERROR: Fails requirement B.\ng(baz{}); // PASS.\n```\n* **Compound requirements** - an expression in braces followed by a trailing return type or type constraint.\n\n```c++\ntemplate \u003ctypename T\u003e\nconcept C = requires(T x) {\n  {*x} -\u003e std::convertible_to\u003ctypename T::inner\u003e; // the type of the expression `*x` is convertible to `T::inner`\n  {x + 1} -\u003e std::same_as\u003cint\u003e; // the expression `x + 1` satisfies `std::same_as\u003cdecltype((x + 1))\u003e`\n  {x * 1} -\u003e std::convertible_to\u003cT\u003e; // the type of the expression `x * 1` is convertible to `T`\n};\n```\n* **Nested requirements** - denoted by the `requires` keyword, specify additional constraints (such as those on local parameter arguments).\n\n```c++\ntemplate \u003ctypename T\u003e\nconcept C = requires(T x) {\n  requires std::same_as\u003csizeof(x), size_t\u003e;\n};\n```\nSee also: [concepts library](#concepts-library).\n\n### Three-way comparison\nC++20 introduces the spaceship operator (`\u003c=\u003e`) as a new way to write comparison functions that reduce boilerplate and help developers define clearer comparison semantics. Defining a three-way comparison operator will autogenerate the other comparison operator functions (i.e. `==`, `!=`, `\u003c`, etc.).\n\nThree orderings are introduced:\n* `std::strong_ordering`: The strong ordering distinguishes between items being equal (identical and interchangeable). Provides `less`, `greater`, `equivalent`, and `equal` ordering. Examples of comparisons: searching for a specific value in a list, values of integers, case-sensitive strings.\n* `std::weak_ordering`: The weak ordering distinguishes between items being equivalent (not identical, but can be interchangeable for the purposes of comparison). Provides `less`, `greater`, and `equivalent` ordering. Examples of comparisons: case-insensitive strings, sorting, comparing some but not all visible members of a class.\n* `std::partial_ordering`: The partial ordering follows the same principle of weak ordering but includes the case when an ordering isn't possible. Provides `less`, `greater`, `equivalent`, and `unordered` ordering. Examples of comparisons: floating-point values (e.g. `NaN`).\n\nA defaulted three-way comparison operator does a member-wise comparison:\n```c++\nstruct foo {\n  int a;\n  bool b;\n  char c;\n\n  // Compare `a` first, then `b`, then `c` ...\n  auto operator\u003c=\u003e(const foo\u0026) const = default;\n};\n\nfoo f1{0, false, 'a'}, f2{0, true, 'b'};\nf1 \u003c f2; // == true\nf1 == f2; // == false\nf1 \u003e= f2; // == false\n```\n\nYou can also define your own comparisons:\n```c++\nstruct foo {\n  int x;\n  bool b;\n  char c;\n  std::strong_ordering operator\u003c=\u003e(const foo\u0026 other) const {\n      return x \u003c=\u003e other.x;\n  }\n};\n\nfoo f1{0, false, 'a'}, f2{0, true, 'b'};\nf1 \u003c f2; // == false\nf1 == f2; // == true\nf1 \u003e= f2; // == true\n```\n\n### Designated initializers\nC-style designated initializer syntax. Any member fields that are not explicitly listed in the designated initializer list are default-initialized.\n```c++\nstruct A {\n  int x;\n  int y;\n  int z = 123;\n};\n\nA a {.x = 1, .z = 2}; // a.x == 1, a.y == 0, a.z == 2\n```\n\n### Template syntax for lambdas\nUse familiar template syntax in lambda expressions.\n```c++\nauto f = []\u003ctypename T\u003e(std::vector\u003cT\u003e v) {\n  // ...\n};\n```\n\n### Range-based for loop with initializer\nThis feature simplifies common code patterns, helps keep scopes tight, and offers an elegant solution to a common lifetime problem.\n```c++\nfor (auto v = std::vector{1, 2, 3}; auto\u0026 e : v) {\n  std::cout \u003c\u003c e;\n}\n// prints \"123\"\n```\n\n### \\[\\[likely\\]\\] and \\[\\[unlikely\\]\\] attributes\nProvides a hint to the optimizer that the labelled statement has a high probability of being executed.\n```c++\nswitch (n) {\ncase 1:\n  // ...\n  break;\n\n[[likely]] case 2:  // n == 2 is considered to be arbitrarily more\n  // ...            // likely than any other value of n\n  break;\n}\n```\n\nIf one of the likely/unlikely attributes appears after the right parenthesis of an if-statement,\nit indicates that the branch is likely/unlikely to have its substatement (body) executed.\n```c++\nint random = get_random_number_between_x_and_y(0, 3);\nif (random \u003e 0) [[likely]] {\n  // body of if statement\n  // ...\n}\n```\n\nIt can also be applied to the substatement (body) of an iteration statement.\n```c++\nwhile (unlikely_truthy_condition) [[unlikely]] {\n  // body of while statement\n  // ...\n}\n```\n\n### Deprecate implicit capture of this\nImplicitly capturing `this` in a lambda capture using `[=]` is now deprecated; prefer capturing explicitly using `[=, this]` or `[=, *this]`.\n```c++\nstruct int_value {\n  int n = 0;\n  auto getter_fn() {\n    // BAD:\n    // return [=]() { return n; };\n\n    // GOOD:\n    return [=, *this]() { return n; };\n  }\n};\n```\n\n### Class types in non-type template parameters\nClasses can now be used in non-type template parameters. Objects passed in as template arguments have the type `const T`, where `T` is the type of the object, and has static storage duration.\n```c++\nstruct foo {\n  foo() = default;\n  constexpr foo(int) {}\n};\n\ntemplate \u003cfoo f = {}\u003e\nauto get_foo() {\n  return f;\n}\n\nget_foo(); // uses implicit constructor\nget_foo\u003cfoo{123}\u003e();\n```\n\n### constexpr virtual functions\nVirtual functions can now be `constexpr` and evaluated at compile-time. `constexpr` virtual functions can override non-`constexpr` virtual functions and vice-versa.\n```c++\nstruct X1 {\n  virtual int f() const = 0;\n};\n\nstruct X2: public X1 {\n  constexpr virtual int f() const { return 2; }\n};\n\nstruct X3: public X2 {\n  virtual int f() const { return 3; }\n};\n\nstruct X4: public X3 {\n  constexpr virtual int f() const { return 4; }\n};\n\nconstexpr X4 x4;\nx4.f(); // == 4\n```\n\n### explicit(bool)\nConditionally select at compile-time whether a constructor is made explicit or not. `explicit(true)` is the same as specifying `explicit`.\n```c++\nstruct foo {\n  // Specify non-integral types (strings, floats, etc.) require explicit construction.\n  template \u003ctypename T\u003e\n  explicit(!std::is_integral_v\u003cT\u003e) foo(T) {}\n};\n\nfoo a = 123; // OK\nfoo b = \"123\"; // ERROR: explicit constructor is not a candidate (explicit specifier evaluates to true)\nfoo c {\"123\"}; // OK\n```\n\n### Immediate functions\nSimilar to `constexpr` functions, but functions with a `consteval` specifier must produce a constant. These are called `immediate functions`.\n```c++\nconsteval int sqr(int n) {\n  return n * n;\n}\n\nconstexpr int r = sqr(100); // OK\nint x = 100;\nint r2 = sqr(x); // ERROR: the value of 'x' is not usable in a constant expression\n                 // OK if `sqr` were a `constexpr` function\n```\n\n### using enum\nBring an enum's members into scope to improve readability. Before:\n```c++\nenum class rgba_color_channel { red, green, blue, alpha };\n\nstd::string_view to_string(rgba_color_channel channel) {\n  switch (channel) {\n    case rgba_color_channel::red:   return \"red\";\n    case rgba_color_channel::green: return \"green\";\n    case rgba_color_channel::blue:  return \"blue\";\n    case rgba_color_channel::alpha: return \"alpha\";\n  }\n}\n```\nAfter:\n```c++\nenum class rgba_color_channel { red, green, blue, alpha };\n\nstd::string_view to_string(rgba_color_channel my_channel) {\n  switch (my_channel) {\n    using enum rgba_color_channel;\n    case red:   return \"red\";\n    case green: return \"green\";\n    case blue:  return \"blue\";\n    case alpha: return \"alpha\";\n  }\n}\n```\n\n### Lambda capture of parameter pack\nCapture parameter packs by value:\n```c++\ntemplate \u003ctypename... Args\u003e\nauto f(Args\u0026\u0026... args){\n    // BY VALUE:\n    return [...args = std::forward\u003cArgs\u003e(args)] {\n        // ...\n    };\n}\n```\nCapture parameter packs by reference:\n```c++\ntemplate \u003ctypename... Args\u003e\nauto f(Args\u0026\u0026... args){\n    // BY REFERENCE:\n    return [\u0026...args = std::forward\u003cArgs\u003e(args)] {\n        // ...\n    };\n}\n```\n\n### char8_t\nProvides a standard type for representing UTF-8 strings.\n```c++\nchar8_t utf8_str[] = u8\"\\u0123\";\n```\n\n### constinit\nThe `constinit` specifier requires that a variable must be initialized at compile-time.\n```c++\nconst char* g() { return \"dynamic initialization\"; }\nconstexpr const char* f(bool p) { return p ? \"constant initializer\" : g(); }\n\nconstinit const char* c = f(true); // OK\nconstinit const char* d = g(false); // ERROR: `g` is not constexpr, so `d` cannot be evaluated at compile-time.\n```\n\n### \\_\\_VA\\_OPT\\_\\_\nHelps support variadic macros by evaluating to the given argument if the variadic macro is non-empty.\n```c++\n#define F(...) f(0 __VA_OPT__(,) __VA_ARGS__)\nF(a, b, c) // replaced by f(0, a, b, c)\nF()        // replaced by f(0)\n```\n\n## C++20 Library Features\n\n### Concepts library\nConcepts are also provided by the standard library for building more complicated concepts. Some of these include:\n\n**Core language concepts:**\n- `same_as` - specifies two types are the same.\n- `derived_from` - specifies that a type is derived from another type.\n- `convertible_to` - specifies that a type is implicitly convertible to another type.\n- `common_with` - specifies that two types share a common type.\n- `integral` - specifies that a type is an integral type.\n- `default_constructible` - specifies that an object of a type can be default-constructed.\n\n **Comparison concepts:**\n- `boolean` - specifies that a type can be used in Boolean contexts.\n- `equality_comparable` - specifies that `operator==` is an equivalence relation.\n\n **Object concepts:**\n- `movable` - specifies that an object of a type can be moved and swapped.\n- `copyable` - specifies that an object of a type can be copied, moved, and swapped.\n- `semiregular` - specifies that an object of a type can be copied, moved, swapped, and default constructed.\n- `regular` - specifies that a type is _regular_, that is, it is both `semiregular` and `equality_comparable`.\n\n **Callable concepts:**\n- `invocable` - specifies that a callable type can be invoked with a given set of argument types.\n- `predicate` - specifies that a callable type is a Boolean predicate.\n\nSee also: [concepts](#concepts).\n\n### Formatting library\nCombine the simplicity of `printf` with the type-safety of `iostream`. Uses braces as placeholders, and supports custom formatting similar to printf-style specifiers.\n```c++\nstd::format(\"{1} {0}\", \"world\", \"hello\"); // == \"hello world\"\n\nint x = 123;\nstd::string str = std::format(\"x: {}\", x); // str == \"x: 123\"\n\n// Format to an output iterator:\nfor (auto x : {1, 2, 3}) {\n  std::format_to(std::ostream_iterator\u003cchar\u003e{std::cout, \"\\n\"}, \"{}\", x);\n}\n```\n\nTo format custom types:\n```c++\nstruct fraction {\n  int numerator;\n  int denominator;\n};\n\ntemplate \u003c\u003e\nstruct std::formatter\u003cfraction\u003e\n{\n    constexpr auto parse(std::format_parse_context\u0026 ctx) {\n      return ctx.begin();\n    }\n\n    auto format(const fraction\u0026 f, std::format_context\u0026 ctx) const {\n      return std::format_to(ctx.out(), \"{0:d}/{1:d}\", f.numerator, f.denominator);\n    }\n};\n\nfraction f{1, 2};\nstd::format(\"{}\", f); // == \"1/2\"\n```\n\n### Synchronized buffered outputstream\nBuffers output operations for the wrapped output stream ensuring synchronization (i.e. no interleaving of output).\n```c++\nstd::osyncstream{std::cout} \u003c\u003c \"The value of x is:\" \u003c\u003c x \u003c\u003c std::endl;\n```\n\n### std::span\nA span is a view (i.e. non-owning) of a container providing bounds-checked access to a contiguous group of elements. Since views do not own their elements they are cheap to construct and copy -- a simplified way to think about views is they are holding references to their data. As opposed to maintaining a pointer/iterator and length field, a span wraps both of those up in a single object.\n\nSpans can be dynamically-sized or fixed-sized (known as their *extent*). Fixed-sized spans benefit from bounds-checking.\n\nSpan doesn't propogate const so to construct a read-only span use `std::span\u003cconst T\u003e`.\n\nExample: using a dynamically-sized span to print integers from various containers.\n```c++\nvoid print_ints(std::span\u003cconst int\u003e ints) {\n    for (const auto n : ints) {\n        std::cout \u003c\u003c n \u003c\u003c std::endl;\n    }\n}\n\nprint_ints(std::vector{ 1, 2, 3 });\nprint_ints(std::array\u003cint, 5\u003e{ 1, 2, 3, 4, 5 });\n\nint a[10] = { 0 };\nprint_ints(a);\n// etc.\n```\n\nExample: a statically-sized span will fail to compile for containers that don't match the extent of the span.\n```c++\nvoid print_three_ints(std::span\u003cconst int, 3\u003e ints) {\n    for (const auto n : ints) {\n        std::cout \u003c\u003c n \u003c\u003c std::endl;\n    }\n}\n\nprint_three_ints(std::vector{ 1, 2, 3 }); // ERROR\nprint_three_ints(std::array\u003cint, 5\u003e{ 1, 2, 3, 4, 5 }); // ERROR\nint a[10] = { 0 };\nprint_three_ints(a); // ERROR\n\nstd::array\u003cint, 3\u003e b = { 1, 2, 3 };\nprint_three_ints(b); // OK\n\n// You can construct a span manually if required:\nstd::vector c{ 1, 2, 3 };\nprint_three_ints(std::span\u003cconst int, 3\u003e{ c.data(), 3 }); // OK: set pointer and length field.\nprint_three_ints(std::span\u003cconst int, 3\u003e{ c.cbegin(), c.cend() }); // OK: use iterator pairs.\n```\n\n### Bit operations\nC++20 provides a new `\u003cbit\u003e` header which provides some bit operations including popcount.\n```c++\nstd::popcount(0u); // 0\nstd::popcount(1u); // 1\nstd::popcount(0b1111'0000u); // 4\n```\n\n### Math constants\nMathematical constants including PI, Euler's number, etc. defined in the `\u003cnumbers\u003e` header.\n```c++\nstd::numbers::pi; // 3.14159...\nstd::numbers::e; // 2.71828...\n```\n\n### std::is_constant_evaluated\nPredicate function which is truthy when it is called in a compile-time context.\n```c++\nconstexpr bool is_compile_time() {\n    return std::is_constant_evaluated();\n}\n\nconstexpr bool a = is_compile_time(); // true\nbool b = is_compile_time(); // false\n```\n\n### std::make_shared supports arrays\n```c++\nauto p = std::make_shared\u003cint[]\u003e(5); // pointer to `int[5]`\n// OR\nauto p = std::make_shared\u003cint[5]\u003e(); // pointer to `int[5]`\n```\n\n### starts_with and ends_with on strings\nStrings (and string views) now have the `starts_with` and `ends_with` member functions to check if a string starts or ends with the given string.\n```c++\nstd::string str = \"foobar\";\nstr.starts_with(\"foo\"); // true\nstr.ends_with(\"baz\"); // false\n```\n\n### Check if associative container has element\nAssociative containers such as sets and maps have a `contains` member function, which can be used instead of the \"find and check end of iterator\" idiom.\n```c++\nstd::map\u003cint, char\u003e map {{1, 'a'}, {2, 'b'}};\nmap.contains(2); // true\nmap.contains(123); // false\n\nstd::set\u003cint\u003e set {1, 2, 3};\nset.contains(2); // true\n```\n\n### std::bit_cast\nA safer way to reinterpret an object from one type to another.\n```c++\nfloat f = 123.0;\nint i = std::bit_cast\u003cint\u003e(f);\n```\n\n### std::midpoint\nCalculate the midpoint of two integers safely (without overflow).\n```c++\nstd::midpoint(1, 3); // == 2\n```\n\n### std::to_array\nConverts the given array/\"array-like\" object to a `std::array`.\n```c++\nstd::to_array(\"foo\"); // returns `std::array\u003cchar, 4\u003e`\nstd::to_array\u003cint\u003e({1, 2, 3}); // returns `std::array\u003cint, 3\u003e`\n\nint a[] = {1, 2, 3};\nstd::to_array(a); // returns `std::array\u003cint, 3\u003e`\n```\n\n### std::bind_front\nBinds the first N arguments (where N is the number of arguments after the given function to `std::bind_front`) to a given free function, lambda, or member function.\n```c++\nconst auto f = [](int a, int b, int c) { return a + b + c; };\nconst auto g = std::bind_front(f, 1, 1);\ng(1); // == 3\n```\n\n### Uniform container erasure\nProvides `std::erase` and/or `std::erase_if` for a variety of STL containers such as string, list, vector, map, etc.\n\nFor erasing by value use `std::erase`, or to specify a predicate when to erase elements use `std::erase_if`. Both functions return the number of erased elements.\n\n```c++\nstd::vector v{0, 1, 0, 2, 0, 3};\nstd::erase(v, 0); // v == {1, 2, 3}\nstd::erase_if(v, [](int n) { return n == 0; }); // v == {1, 2, 3}\n```\n\n### Three-way comparison helpers\nHelper functions for giving names to comparison results:\n```c++\nstd::is_eq(0 \u003c=\u003e 0); // == true\nstd::is_lteq(0 \u003c=\u003e 1); // == true\nstd::is_gt(0 \u003c=\u003e 1); // == false\n```\n\nSee also: [three-way comparison](#three-way-comparison).\n\n### std::lexicographical_compare_three_way\nLexicographically compares two ranges using three-way comparison and produces a result of the strongest applicable comparison category type.\n```c++\nstd::vector a{0, 0, 0}, b{0, 0, 0}, c{1, 1, 1};\n\nauto cmp_ab = std::lexicographical_compare_three_way(\n    a.begin(), a.end(), b.begin(), b.end());\nstd::is_eq(cmp_ab); // == true\n\nauto cmp_ac = std::lexicographical_compare_three_way(\n    a.begin(), a.end(), c.begin(), c.end());\nstd::is_lt(cmp_ac); // == true\n```\n\nSee also: [three-way comparison](#three-way-comparison), [three-way comparison helpers](#three-way-comparison-helpers).\n\n## C++17 Language Features\n\n### Template argument deduction for class templates\nAutomatic template argument deduction much like how it's done for functions, but now including class constructors.\n```c++\ntemplate \u003ctypename T = float\u003e\nstruct MyContainer {\n  T val;\n  MyContainer() : val{} {}\n  MyContainer(T val) : val{val} {}\n  // ...\n};\nMyContainer c1 {1}; // OK MyContainer\u003cint\u003e\nMyContainer c2; // OK MyContainer\u003cfloat\u003e\n```\n\n### Declaring non-type template parameters with auto\nFollowing the deduction rules of `auto`, while respecting the non-type template parameter list of allowable types[\\*], template arguments can be deduced from the types of its arguments:\n```c++\ntemplate \u003cauto... seq\u003e\nstruct my_integer_sequence {\n  // Implementation here ...\n};\n\n// Explicitly pass type `int` as template argument.\nauto seq = std::integer_sequence\u003cint, 0, 1, 2\u003e();\n// Type is deduced to be `int`.\nauto seq2 = my_integer_sequence\u003c0, 1, 2\u003e();\n```\n\\* - For example, you cannot use a `double` as a template parameter type, which also makes this an invalid deduction using `auto`.\n\n### Folding expressions\nA fold expression performs a fold of a template parameter pack over a binary operator.\n* An expression of the form `(... op e)` or `(e op ...)`, where `op` is a fold-operator and `e` is an unexpanded parameter pack, are called _unary folds_.\n* An expression of the form `(e1 op ... op e2)`, where `op` are fold-operators, is called a _binary fold_. Either `e1` or `e2` is an unexpanded parameter pack, but not both.\n```c++\ntemplate \u003ctypename... Args\u003e\nbool logicalAnd(Args... args) {\n    // Binary folding.\n    return (true \u0026\u0026 ... \u0026\u0026 args);\n}\nbool b = true;\nbool\u0026 b2 = b;\nlogicalAnd(b, b2, true); // == true\n```\n```c++\ntemplate \u003ctypename... Args\u003e\nauto sum(Args... args) {\n    // Unary folding.\n    return (... + args);\n}\nsum(1.0, 2.0f, 3); // == 6.0\n```\n\n### New rules for auto deduction from braced-init-list\nChanges to `auto` deduction when used with the uniform initialization syntax. Previously, `auto x {3};` deduces a `std::initializer_list\u003cint\u003e`, which now deduces to `int`.\n```c++\nauto x1 {1, 2, 3}; // error: not a single element\nauto x2 = {1, 2, 3}; // x2 is std::initializer_list\u003cint\u003e\nauto x3 {3}; // x3 is int\nauto x4 {3.0}; // x4 is double\n```\n\n### constexpr lambda\nCompile-time lambdas using `constexpr`.\n```c++\nauto identity = [](int n) constexpr { return n; };\nstatic_assert(identity(123) == 123);\n```\n```c++\nconstexpr auto add = [](int x, int y) {\n  auto L = [=] { return x; };\n  auto R = [=] { return y; };\n  return [=] { return L() + R(); };\n};\n\nstatic_assert(add(1, 2)() == 3);\n```\n```c++\nconstexpr int addOne(int n) {\n  return [n] { return n + 1; }();\n}\n\nstatic_assert(addOne(1) == 2);\n```\n\n### Lambda capture `this` by value\nCapturing `this` in a lambda's environment was previously reference-only. An example of where this is problematic is asynchronous code using callbacks that require an object to be available, potentially past its lifetime. `*this` (C++17) will now make a copy of the current object, while `this` (C++11) continues to capture by reference.\n```c++\nstruct MyObj {\n  int value {123};\n  auto getValueCopy() {\n    return [*this] { return value; };\n  }\n  auto getValueRef() {\n    return [this] { return value; };\n  }\n};\nMyObj mo;\nauto valueCopy = mo.getValueCopy();\nauto valueRef = mo.getValueRef();\nmo.value = 321;\nvalueCopy(); // 123\nvalueRef(); // 321\n```\n\n### Inline variables\nThe inline specifier can be applied to variables as well as to functions. A variable declared inline has the same semantics as a function declared inline.\n```c++\n// Disassembly example using compiler explorer.\nstruct S { int x; };\ninline S x1 = S{321}; // mov esi, dword ptr [x1]\n                      // x1: .long 321\n\nS x2 = S{123};        // mov eax, dword ptr [.L_ZZ4mainE2x2]\n                      // mov dword ptr [rbp - 8], eax\n                      // .L_ZZ4mainE2x2: .long 123\n```\n\nIt can also be used to declare and define a static member variable, such that it does not need to be initialized in the source file.\n```c++\nstruct S {\n  S() : id{count++} {}\n  ~S() { count--; }\n  int id;\n  static inline int count{0}; // declare and initialize count to 0 within the class\n};\n```\n\n### Nested namespaces\nUsing the namespace resolution operator to create nested namespace definitions.\n```c++\nnamespace A {\n  namespace B {\n    namespace C {\n      int i;\n    }\n  }\n}\n```\n\nThe code above can be written like this:\n```c++\nnamespace A::B::C {\n  int i;\n}\n```\n\n### Structured bindings\nA proposal for de-structuring initialization, that would allow writing `auto [ x, y, z ] = expr;` where the type of `expr` was a tuple-like object, whose elements would be bound to the variables `x`, `y`, and `z` (which this construct declares). _Tuple-like objects_ include [`std::tuple`](#tuples), `std::pair`, [`std::array`](#stdarray), and aggregate structures.\n```c++\nusing Coordinate = std::pair\u003cint, int\u003e;\nCoordinate origin() {\n  return Coordinate{0, 0};\n}\n\nconst auto [ x, y ] = origin();\nx; // == 0\ny; // == 0\n```\n```c++\nstd::unordered_map\u003cstd::string, int\u003e mapping {\n  {\"a\", 1},\n  {\"b\", 2},\n  {\"c\", 3}\n};\n\n// Destructure by reference.\nfor (const auto\u0026 [key, value] : mapping) {\n  // Do something with key and value\n}\n```\n\n### Selection statements with initializer\nNew versions of the `if` and `switch` statements which simplify common code patterns and help users keep scopes tight.\n```c++\n{\n  std::lock_guard\u003cstd::mutex\u003e lk(mx);\n  if (v.empty()) v.push_back(val);\n}\n// vs.\nif (std::lock_guard\u003cstd::mutex\u003e lk(mx); v.empty()) {\n  v.push_back(val);\n}\n```\n```c++\nFoo gadget(args);\nswitch (auto s = gadget.status()) {\n  case OK: gadget.zip(); break;\n  case Bad: throw BadFoo(s.message());\n}\n// vs.\nswitch (Foo gadget(args); auto s = gadget.status()) {\n  case OK: gadget.zip(); break;\n  case Bad: throw BadFoo(s.message());\n}\n```\n\n### constexpr if\nWrite code that is instantiated depending on a compile-time condition.\n```c++\ntemplate \u003ctypename T\u003e\nconstexpr bool isIntegral() {\n  if constexpr (std::is_integral\u003cT\u003e::value) {\n    return true;\n  } else {\n    return false;\n  }\n}\nstatic_assert(isIntegral\u003cint\u003e() == true);\nstatic_assert(isIntegral\u003cchar\u003e() == true);\nstatic_assert(isIntegral\u003cdouble\u003e() == false);\nstruct S {};\nstatic_assert(isIntegral\u003cS\u003e() == false);\n```\n\n### UTF-8 character literals\nA character literal that begins with `u8` is a character literal of type `char`. The value of a UTF-8 character literal is equal to its ISO 10646 code point value.\n```c++\nchar x = u8'x';\n```\n\n### Direct list initialization of enums\nEnums can now be initialized using braced syntax.\n```c++\nenum byte : unsigned char {};\nbyte b {0}; // OK\nbyte c {-1}; // ERROR\nbyte d = byte{1}; // OK\nbyte e = byte{256}; // ERROR\n```\n\n### \\[\\[fallthrough\\]\\], \\[\\[nodiscard\\]\\], \\[\\[maybe_unused\\]\\] attributes\nC++17 introduces three new attributes: `[[fallthrough]]`, `[[nodiscard]]` and `[[maybe_unused]]`.\n* `[[fallthrough]]` indicates to the compiler that falling through in a switch statement is intended behavior. This attribute may only be used in a switch statement, and must be placed before the next case/default label.\n```c++\nswitch (n) {\n  case 1: \n    // ...\n    [[fallthrough]];\n  case 2:\n    // ...\n    break;\n  case 3:\n    // ...\n    [[fallthrough]];\n  default:\n    // ...\n}\n```\n\n* `[[nodiscard]]` issues a warning when either a function or class has this attribute and its return value is discarded.\n```c++\n[[nodiscard]] bool do_something() {\n  return is_success; // true for success, false for failure\n}\n\ndo_something(); // warning: ignoring return value of 'bool do_something()',\n                // declared with attribute 'nodiscard'\n```\n```c++\n// Only issues a warning when `error_info` is returned by value.\nstruct [[nodiscard]] error_info {\n  // ...\n};\n\nerror_info do_something() {\n  error_info ei;\n  // ...\n  return ei;\n}\n\ndo_something(); // warning: ignoring returned value of type 'error_info',\n                // declared with attribute 'nodiscard'\n```\n\n* `[[maybe_unused]]` indicates to the compiler that a variable or parameter might be unused and is intended.\n```c++\nvoid my_callback(std::string msg, [[maybe_unused]] bool error) {\n  // Don't care if `msg` is an error message, just log it.\n  log(msg);\n}\n```\n\n### \\_\\_has\\_include\n\n`__has_include (operand)` operator may be used in `#if` and `#elif` expressions to check whether a header or source file (`operand`) is available for inclusion or not.\n\nOne use case of this would be using two libraries that work the same way, using the backup/experimental one if the preferred one is not found on the system.\n\n```c++\n#ifdef __has_include\n#  if __has_include(\u003coptional\u003e)\n#    include \u003coptional\u003e\n#    define have_optional 1\n#  elif __has_include(\u003cexperimental/optional\u003e)\n#    include \u003cexperimental/optional\u003e\n#    define have_optional 1\n#    define experimental_optional\n#  else\n#    define have_optional 0\n#  endif\n#endif\n```\n\nIt can also be used to include headers existing under different names or locations on various platforms, without knowing which platform the program is running on, OpenGL headers are a good example for this which are located in `OpenGL\\` directory on macOS and `GL\\` on other platforms.\n\n```c++\n#ifdef __has_include\n#  if __has_include(\u003cOpenGL/gl.h\u003e)\n#    include \u003cOpenGL/gl.h\u003e\n#    include \u003cOpenGL/glu.h\u003e\n#  elif __has_include(\u003cGL/gl.h\u003e)\n#    include \u003cGL/gl.h\u003e\n#    include \u003cGL/glu.h\u003e\n#  else\n#    error No suitable OpenGL headers found.\n# endif\n#endif\n```\n\n### Class template argument deduction\n*Class template argument deduction* (CTAD) allows the compiler to deduce template arguments from constructor arguments.\n```c++\nstd::vector v{ 1, 2, 3 }; // deduces std::vector\u003cint\u003e\n\nstd::mutex mtx;\nauto lck = std::lock_guard{ mtx }; // deduces to std::lock_guard\u003cstd::mutex\u003e\n\nauto p = new std::pair{ 1.0, 2.0 }; // deduces to std::pair\u003cdouble, double\u003e*\n```\n\nFor user-defined types, *deduction guides* can be used to guide the compiler how to deduce template arguments if applicable:\n```c++\ntemplate \u003ctypename T\u003e\nstruct container {\n  container(T t) {}\n\n  template \u003ctypename Iter\u003e\n  container(Iter beg, Iter end);\n};\n\n// deduction guide\ntemplate \u003ctypename Iter\u003e\ncontainer(Iter b, Iter e) -\u003e container\u003ctypename std::iterator_traits\u003cIter\u003e::value_type\u003e;\n\ncontainer a{ 7 }; // OK: deduces container\u003cint\u003e\n\nstd::vector\u003cdouble\u003e v{ 1.0, 2.0, 3.0 };\nauto b = container{ v.begin(), v.end() }; // OK: deduces container\u003cdouble\u003e\n\ncontainer c{ 5, 6 }; // ERROR: std::iterator_traits\u003cint\u003e::value_type is not a type\n```\n\n## C++17 Library Features\n\n### std::variant\nThe class template `std::variant` represents a type-safe `union`. An instance of `std::variant` at any given time holds a value of one of its alternative types (it's also possible for it to be valueless).\n```c++\nstd::variant\u003cint, double\u003e v{ 12 };\nstd::get\u003cint\u003e(v); // == 12\nstd::get\u003c0\u003e(v); // == 12\nv = 12.0;\nstd::get\u003cdouble\u003e(v); // == 12.0\nstd::get\u003c1\u003e(v); // == 12.0\n```\n\n### std::optional\nThe class template `std::optional` manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.\n```c++\nstd::optional\u003cstd::string\u003e create(bool b) {\n  if (b) {\n    return \"Godzilla\";\n  } else {\n    return {};\n  }\n}\n\ncreate(false).value_or(\"empty\"); // == \"empty\"\ncreate(true).value(); // == \"Godzilla\"\n// optional-returning factory functions are usable as conditions of while and if\nif (auto str = create(true)) {\n  // ...\n}\n```\n\n### std::any\nA type-safe container for single values of any type.\n```c++\nstd::any x {5};\nx.has_value() // == true\nstd::any_cast\u003cint\u003e(x) // == 5\nstd::any_cast\u003cint\u0026\u003e(x) = 10;\nstd::any_cast\u003cint\u003e(x) // == 10\n```\n\n### std::string_view\nA non-owning reference to a string. Useful for providing an abstraction on top of strings (e.g. for parsing).\n```c++\n// Regular strings.\nstd::string_view cppstr {\"foo\"};\n// Wide strings.\nstd::wstring_view wcstr_v {L\"baz\"};\n// Character arrays.\nchar array[3] = {'b', 'a', 'r'};\nstd::string_view array_v(array, std::size(array));\n```\n```c++\nstd::string str {\"   trim me\"};\nstd::string_view v {str};\nv.remove_prefix(std::min(v.find_first_not_of(\" \"), v.size()));\nstr; //  == \"   trim me\"\nv; // == \"trim me\"\n```\n\n### std::invoke\nInvoke a `Callable` object with parameters. Examples of *callable* objects are `std::function` or lambdas; objects that can be called similarly to a regular function.\n```c++\ntemplate \u003ctypename Callable\u003e\nclass Proxy {\n  Callable c_;\n\npublic:\n  Proxy(Callable c) : c_{ std::move(c) } {}\n\n  template \u003ctypename... Args\u003e\n  decltype(auto) operator()(Args\u0026\u0026... args) {\n    // ...\n    return std::invoke(c_, std::forward\u003cArgs\u003e(args)...);\n  }\n};\n\nconst auto add = [](int x, int y) { return x + y; };\nProxy p{ add };\np(1, 2); // == 3\n```\n\n### std::apply\nInvoke a `Callable` object with a tuple of arguments.\n```c++\nauto add = [](int x, int y) {\n  return x + y;\n};\nstd::apply(add, std::make_tuple(1, 2)); // == 3\n```\n\n### std::filesystem\nThe new `std::filesystem` library provides a standard way to manipulate files, directories, and paths in a filesystem.\n\nHere, a big file is copied to a temporary path if there is available space:\n```c++\nconst auto bigFilePath {\"bigFileToCopy\"};\nif (std::filesystem::exists(bigFilePath)) {\n  const auto bigFileSize {std::filesystem::file_size(bigFilePath)};\n  std::filesystem::path tmpPath {\"/tmp\"};\n  if (std::filesystem::space(tmpPath).available \u003e bigFileSize) {\n    std::filesystem::create_directory(tmpPath.append(\"example\"));\n    std::filesystem::copy_file(bigFilePath, tmpPath.append(\"newFile\"));\n  }\n}\n```\n\n### std::byte\nThe new `std::byte` type provides a standard way of representing data as a byte. Benefits of using `std::byte` over `char` or `unsigned char` is that it is not a character type, and is also not an arithmetic type; while the only operator overloads available are bitwise operations.\n```c++\nstd::byte a {0};\nstd::byte b {0xFF};\nint i = std::to_integer\u003cint\u003e(b); // 0xFF\nstd::byte c = a \u0026 b;\nint j = std::to_integer\u003cint\u003e(c); // 0\n```\nNote that `std::byte` is simply an enum, and braced initialization of enums become possible thanks to [direct-list-initialization of enums](#direct-list-initialization-of-enums).\n\n### Splicing for maps and sets\nMoving nodes and merging containers without the overhead of expensive copies, moves, or heap allocations/deallocations.\n\nMoving elements from one map to another:\n```c++\nstd::map\u003cint, string\u003e src {{1, \"one\"}, {2, \"two\"}, {3, \"buckle my shoe\"}};\nstd::map\u003cint, string\u003e dst {{3, \"three\"}};\ndst.insert(src.extract(src.find(1))); // Cheap remove and insert of { 1, \"one\" } from `src` to `dst`.\ndst.insert(src.extract(2)); // Cheap remove and insert of { 2, \"two\" } from `src` to `dst`.\n// dst == { { 1, \"one\" }, { 2, \"two\" }, { 3, \"three\" } };\n```\n\nInserting an entire set:\n```c++\nstd::set\u003cint\u003e src {1, 3, 5};\nstd::set\u003cint\u003e dst {2, 4, 5};\ndst.merge(src);\n// src == { 5 }\n// dst == { 1, 2, 3, 4, 5 }\n```\n\nInserting elements which outlive the container:\n```c++\nauto elementFactory() {\n  std::set\u003c...\u003e s;\n  s.emplace(...);\n  return s.extract(s.begin());\n}\ns2.insert(elementFactory());\n```\n\nChanging the key of a map element:\n```c++\nstd::map\u003cint, string\u003e m {{1, \"one\"}, {2, \"two\"}, {3, \"three\"}};\nauto e = m.extract(2);\ne.key() = 4;\nm.insert(std::move(e));\n// m == { { 1, \"one\" }, { 3, \"three\" }, { 4, \"two\" } }\n```\n\n### Parallel algorithms\nMany of the STL algorithms, such as the `copy`, `find` and `sort` methods, started to support the *parallel execution policies*: `seq`, `par` and `par_unseq` which translate to \"sequentially\", \"parallel\" and \"parallel unsequenced\".\n\n```c++\nstd::vector\u003cint\u003e longVector;\n// Find element using parallel execution policy\nauto result1 = std::find(std::execution::par, std::begin(longVector), std::end(longVector), 2);\n// Sort elements using sequential execution policy\nauto result2 = std::sort(std::execution::seq, std::begin(longVector), std::end(longVector));\n```\n\n### std::sample\nSamples n elements in the given sequence (without replacement) where every element has an equal chance of being selected.\n```c++\nconst std::string ALLOWED_CHARS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nstd::string guid;\n// Sample 5 characters from ALLOWED_CHARS.\nstd::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid),\n  5, std::mt19937{ std::random_device{}() });\n\nstd::cout \u003c\u003c guid; // e.g. G1fW2\n```\n\n### std::clamp\nClamp given value between a lower and upper bound.\n```c++\nstd::clamp(42, -1, 1); // == 1\nstd::clamp(-42, -1, 1); // == -1\nstd::clamp(0, -1, 1); // == 0\n\n// `std::clamp` also accepts a custom comparator:\nstd::clamp(0, -1, 1, std::less\u003c\u003e{}); // == 0\n```\n\n### std::reduce\nFold over a given range of elements. Conceptually similar to `std::accumulate`, but `std::reduce` will perform the fold in parallel. Due to the fold being done in parallel, if you specify a binary operation, it is required to be associative and commutative. A given binary operation also should not change any element or invalidate any iterators within the given range.\n\nThe default binary operation is std::plus with an initial value of 0.\n```c++\nconst std::array\u003cint, 3\u003e a{ 1, 2, 3 };\nstd::reduce(std::cbegin(a), std::cend(a)); // == 6\n// Using a custom binary op:\nstd::reduce(std::cbegin(a), std::cend(a), 1, std::multiplies\u003c\u003e{}); // == 6\n```\nAdditionally you can specify transformations for reducers:\n```c++\nstd::transform_reduce(std::cbegin(a), std::cend(a), 0, std::plus\u003c\u003e{}, times_ten); // == 60\n\nconst std::array\u003cint, 3\u003e b{ 1, 2, 3 };\nconst auto product_times_ten = [](const auto a, const auto b) { return a * b * 10; };\n\nstd::transform_reduce(std::cbegin(a), std::cend(a), std::cbegin(b), 0, std::plus\u003c\u003e{}, product_times_ten); // == 140\n```\n\n### Prefix sum algorithms\nSupport for prefix sums (both inclusive and exclusive scans) along with transformations.\n```c++\nconst std::array\u003cint, 3\u003e a{ 1, 2, 3 };\n\nstd::inclusive_scan(std::cbegin(a), std::cend(a),\n    std::ostream_iterator\u003cint\u003e{ std::cout, \" \" }, std::plus\u003c\u003e{}); // 1 3 6\n\nstd::exclusive_scan(std::cbegin(a), std::cend(a),\n    std::ostream_iterator\u003cint\u003e{ std::cout, \" \" }, 0, std::plus\u003c\u003e{}); // 0 1 3\n\nconst auto times_ten = [](const auto n) { return n * 10; };\n\nstd::transform_inclusive_scan(std::cbegin(a), std::cend(a),\n    std::ostream_iterator\u003cint\u003e{ std::cout, \" \" }, std::plus\u003c\u003e{}, times_ten); // 10 30 60\n\nstd::transform_exclusive_scan(std::cbegin(a), std::cend(a),\n    std::ostream_iterator\u003cint\u003e{ std::cout, \" \" }, 0, std::plus\u003c\u003e{}, times_ten); // 0 10 30\n```\n\n### GCD and LCM\nGreatest common divisor (GCD) and least common multiple (LCM).\n```c++\nconst int p = 9;\nconst int q = 3;\nstd::gcd(p, q); // == 3\nstd::lcm(p, q); // == 9\n```\n\n### std::not_fn\nUtility function that returns the negation of the result of the given function.\n```c++\nconst std::ostream_iterator\u003cint\u003e ostream_it{ std::cout, \" \" };\nconst auto is_even = [](const auto n) { return n % 2 == 0; };\nstd::vector\u003cint\u003e v{ 0, 1, 2, 3, 4 };\n\n// Print all even numbers.\nstd::copy_if(std::cbegin(v), std::cend(v), ostream_it, is_even); // 0 2 4\n// Print all odd (not even) numbers.\nstd::copy_if(std::cbegin(v), std::cend(v), ostream_it, std::not_fn(is_even)); // 1 3\n```\n\n### String conversion to/from numbers\nConvert integrals and floats to a string or vice-versa. Conversions are non-throwing, do not allocate, and are more secure than the equivalents from the C standard library.\n\nUsers are responsible for allocating enough storage required for `std::to_chars`, or the function will fail by setting the error code object in its return value.\n\nThese functions allow you to optionally pass a base (defaults to base-10) or a format specifier for floating type input.\n\n* `std::to_chars` returns a (non-const) char pointer which is one-past-the-end of the string that the function wrote to inside the given buffer, and an error code object.\n* `std::from_chars` returns a const char pointer which on success is equal to the end pointer passed to the function, and an error code object.\n\nBoth error code objects returned from these functions are equal to the default-initialized error code object on success.\n\nConvert the number `123` to a `std::string`:\n```c++\nconst int n = 123;\n\n// Can use any container, string, array, etc.\nstd::string str;\nstr.resize(3); // hold enough storage for each digit of `n`\n\nconst auto [ ptr, ec ] = std::to_chars(str.data(), str.data() + str.size(), n);\n\nif (ec == std::errc{}) { std::cout \u003c\u003c str \u003c\u003c std::endl; } // 123\nelse { /* handle failure */ }\n```\n\nConvert from a `std::string` with value `\"123\"` to an integer:\n```c++\nconst std::string str{ \"123\" };\nint n;\n\nconst auto [ ptr, ec ] = std::from_chars(str.data(), str.data() + str.size(), n);\n\nif (ec == std::errc{}) { std::cout \u003c\u003c n \u003c\u003c std::endl; } // 123\nelse { /* handle failure */ }\n```\n\n### Rounding functions for chrono durations and timepoints\nProvides abs, round, ceil, and floor helper functions for `std::chrono::duration` and `std::chrono::time_point`.\n```c++\nusing seconds = std::chrono::seconds;\nstd::chrono::milliseconds d{ 5500 };\nstd::chrono::abs(d); // == 5s\nstd::chrono::round\u003cseconds\u003e(d); // == 6s\nstd::chrono::ceil\u003cseconds\u003e(d); // == 6s\nstd::chrono::floor\u003cseconds\u003e(d); // == 5s\n```\n\n## C++14 Language Features\n\n### Binary literals\nBinary literals provide a convenient way to represent a base-2 number.\nIt is possible to separate digits with `'`.\n```c++\n0b110 // == 6\n0b1111'1111 // == 255\n```\n\n### Generic lambda expressions\nC++14 now allows the `auto` type-specifier in the parameter list, enabling polymorphic lambdas.\n```c++\nauto identity = [](auto x) { return x; };\nint three = identity(3); // == 3\nstd::string foo = identity(\"foo\"); // == \"foo\"\n```\n\n### Lambda capture initializers\nThis allows creating lambda captures initialized with arbitrary expressions. The name given to the captured value does not need to be related to any variables in the enclosing scopes and introduces a new name inside the lambda body. The initializing expression is evaluated when the lambda is _created_ (not when it is _invoked_).\n```c++\nint factory(int i) { return i * 10; }\nauto f = [x = factory(2)] { return x; }; // returns 20\n\nauto generator = [x = 0] () mutable {\n  // this would not compile without 'mutable' as we are modifying x on each call\n  return x++;\n};\nauto a = generator(); // == 0\nauto b = generator(); // == 1\nauto c = generator(); // == 2\n```\nBecause it is now possible to _move_ (or _forward_) values into a lambda that could previously be only captured by copy or reference we can now capture move-only types in a lambda by value. Note that in the below example the `p` in the capture-list of `task2` on the left-hand-side of `=` is a new variable private to the lambda body and does not refer to the original `p`.\n```c++\nauto p = std::make_unique\u003cint\u003e(1);\n\nauto task1 = [=] { *p = 5; }; // ERROR: std::unique_ptr cannot be copied\n// vs.\nauto task2 = [p = std::move(p)] { *p = 5; }; // OK: p is move-constructed into the closure object\n// the original p is empty after task2 is created\n```\nUsing this reference-captures can have different names than the referenced variable.\n```c++\nauto x = 1;\nauto f = [\u0026r = x, x = x * 10] {\n  ++r;\n  return r + x;\n};\nf(); // sets x to 2 and returns 12\n```\n\n### Return type deduction\nUsing an `auto` return type in C++14, the compiler will attempt to deduce the type for you. With lambdas, you can now deduce its return type using `auto`, which makes returning a deduced reference or rvalue reference possible.\n```c++\n// Deduce return type as `int`.\nauto f(int i) {\n return i;\n}\n```\n```c++\ntemplate \u003ctypename T\u003e\nauto\u0026 f(T\u0026 t) {\n  return t;\n}\n\n// Returns a reference to a deduced type.\nauto g = [](auto\u0026 x) -\u003e auto\u0026 { return f(x); };\nint y = 123;\nint\u0026 z = g(y); // reference to `y`\n```\n\n### decltype(auto)\nThe `decltype(auto)` type-specifier also deduces a type like `auto` does. However, it deduces return types while keeping their references and cv-qualifiers, while `auto` will not.\n```c++\nconst int x = 0;\nauto x1 = x; // int\ndecltype(auto) x2 = x; // const int\nint y = 0;\nint\u0026 y1 = y;\nauto y2 = y1; // int\ndecltype(auto) y3 = y1; // int\u0026\nint\u0026\u0026 z = 0;\nauto z1 = std::move(z); // int\ndecltype(auto) z2 = std::move(z); // int\u0026\u0026\n```\n```c++\n// Note: Especially useful for generic code!\n\n// Return type is `int`.\nauto f(const int\u0026 i) {\n return i;\n}\n\n// Return type is `const int\u0026`.\ndecltype(auto) g(const int\u0026 i) {\n return i;\n}\n\nint x = 123;\nstatic_assert(std::is_same\u003cconst int\u0026, decltype(f(x))\u003e::value == 0);\nstatic_assert(std::is_same\u003cint, decltype(f(x))\u003e::value == 1);\nstatic_assert(std::is_same\u003cconst int\u0026, decltype(g(x))\u003e::value == 1);\n```\n\nSee also: [`decltype (C++11)`](#decltype).\n\n### Relaxing constraints on constexpr functions\nIn C++11, `constexpr` function bodies could only contain a very limited set of syntaxes, including (but not limited to): `typedef`s, `using`s, and a single `return` statement. In C++14, the set of allowable syntaxes expands greatly to include the most common syntax such as `if` statements, multiple `return`s, loops, etc.\n```c++\nconstexpr int factorial(int n) {\n  if (n \u003c= 1) {\n    return 1;\n  } else {\n    return n * factorial(n - 1);\n  }\n}\nfactorial(5); // == 120\n```\n\n### Variable templates\nC++14 allows variables to be templated:\n\n```c++\ntemplate\u003cclass T\u003e\nconstexpr T pi = T(3.1415926535897932385);\ntemplate\u003cclass T\u003e\nconstexpr T e  = T(2.7182818284590452353);\n```\n\n### [[deprecated]] attribute\nC++14 introduces the `[[deprecated]]` attribute to indicate that a unit (function, class, etc.) is discouraged and likely yield compilation warnings. If a reason is provided, it will be included in the warnings.\n```c++\n[[deprecated]]\nvoid old_method();\n[[deprecated(\"Use new_method instead\")]]\nvoid legacy_method();\n```\n\n## C++14 Library Features\n\n### User-defined literals for standard library types\nNew user-defined literals for standard library types, including new built-in literals for `chrono` and `basic_string`. These can be `constexpr` meaning they can be used at compile-time. Some uses for these literals include compile-time integer parsing, binary literals, and imaginary number literals.\n```c++\nusing namespace std::chrono_literals;\nauto day = 24h;\nday.count(); // == 24\nstd::chrono::duration_cast\u003cstd::chrono::minutes\u003e(day).count(); // == 1440\n```\n\n### Compile-time integer sequences\nThe class template `std::integer_sequence` represents a compile-time sequence of integers. There are a few helpers built on top:\n* `std::make_integer_sequence\u003cT, N\u003e` - creates a sequence of `0, ..., N - 1` with type `T`.\n* `std::index_sequence_for\u003cT...\u003e` - converts a template parameter pack into an integer sequence.\n\nConvert an array into a tuple:\n```c++\ntemplate\u003ctypename Array, std::size_t... I\u003e\ndecltype(auto) a2t_impl(const Array\u0026 a, std::integer_sequence\u003cstd::size_t, I...\u003e) {\n  return std::make_tuple(a[I]...);\n}\n\ntemplate\u003ctypename T, std::size_t N, typename Indices = std::make_index_sequence\u003cN\u003e\u003e\ndecltype(auto) a2t(const std::array\u003cT, N\u003e\u0026 a) {\n  return a2t_impl(a, Indices());\n}\n```\n\n### std::make_unique\n`std::make_unique` is the recommended way to create instances of `std::unique_ptr`s due to the following reasons:\n* Avoid having to use the `new` operator.\n* Prevents code repetition when specifying the underlying type the pointer shall hold.\n* Most importantly, it provides exception-safety. Suppose we were calling a function `foo` like so:\n```c++\nfoo(std::unique_ptr\u003cT\u003e{new T{}}, function_that_throws(), std::unique_ptr\u003cT\u003e{new T{}});\n```\nThe compiler is free to call `new T{}`, then `function_that_throws()`, and so on... Since we have allocated data on the heap in the first construction of a `T`, we have introduced a leak here. With `std::make_unique`, we are given exception-safety:\n```c++\nfoo(std::make_unique\u003cT\u003e(), function_that_throws(), std::make_unique\u003cT\u003e());\n```\n\nSee the section on [smart pointers (C++11)](#smart-pointers) for more information on `std::unique_ptr` and `std::shared_ptr`.\n\n## C++11 Language Features\n\n### Move semantics\nMoving an object means to transfer ownership of some resource it manages to another object.\n\nThe first benefit of move semantics is performance optimization. When an object is about to reach the end of its lifetime, either because it's a temporary or by explicitly calling `std::move`, a move is often a cheaper way to transfer resources. For example, moving a `std::vector` is just copying some pointers and internal state over to the new vector -- copying would involve having to copy every single contained element in the vector, which is expensive and unnecessary if the old vector will soon be destroyed.\n\nMoves also make it possible for non-copyable types such as `std::unique_ptr`s ([smart pointers](#smart-pointers)) to guarantee at the language level that there is only ever one instance of a resource being managed at a time, while being able to transfer an instance between scopes.\n\nSee the sections on: [rvalue references](#rvalue-references), [special member functions for move semantics](#special-member-functions-for-move-semantics), [`std::move`](#stdmove), [`std::forward`](#stdforward), [`forwarding references`](#forwarding-references).\n\n### Rvalue references\nC++11 introduces a new reference termed the _rvalue reference_. An rvalue reference to `T`, which is a non-template type parameter (such as `int`, or a user-defined type), is created with the syntax `T\u0026\u0026`. Rvalue references only bind to rvalues.\n\nType deduction with lvalues and rvalues:\n```c++\nint x = 0; // `x` is an lvalue of type `int`\nint\u0026 xl = x; // `xl` is an lvalue of type `int\u0026`\nint\u0026\u0026 xr = x; // compiler error -- `x` is an lvalue\nint\u0026\u0026 xr2 = 0; // `xr2` is an lvalue of type `int\u0026\u0026` -- binds to the rvalue temporary, `0`\n\nvoid f(int\u0026 x) {}\nvoid f(int\u0026\u0026 x) {}\n\nf(x);  // calls f(int\u0026)\nf(xl); // calls f(int\u0026)\nf(3);  // calls f(int\u0026\u0026)\nf(std::move(x)); // calls f(int\u0026\u0026)\n\nf(xr2);           // calls f(int\u0026)\nf(std::move(xr2)); // calls f(int\u0026\u0026 x)\n```\n\nSee also: [`std::move`](#stdmove), [`std::forward`](#stdforward), [`forwarding references`](#forwarding-references).\n\n### Forwarding references\nAlso known (unofficially) as _universal references_. A forwarding reference is created with the syntax `T\u0026\u0026` where `T` is a template type parameter, or using `auto\u0026\u0026`. This enables _perfect forwarding_: the ability to pass arguments while maintaining their value category (e.g. lvalues stay as lvalues, temporaries are forwarded as rvalues).\n\nForwarding references allow a reference to bind to either an lvalue or rvalue depending on the type. Forwarding references follow the rules of _reference collapsing_:\n* `T\u0026 \u0026` becomes `T\u0026`\n* `T\u0026 \u0026\u0026` becomes `T\u0026`\n* `T\u0026\u0026 \u0026` becomes `T\u0026`\n* `T\u0026\u0026 \u0026\u0026` becomes `T\u0026\u0026`\n\n`auto` type deduction with lvalues and rvalues:\n```c++\nint x = 0; // `x` is an lvalue of type `int`\nauto\u0026\u0026 al = x; // `al` is an lvalue of type `int\u0026` -- binds to the lvalue, `x`\nauto\u0026\u0026 ar = 0; // `ar` is an lvalue of type `int\u0026\u0026` -- binds to the rvalue temporary, `0`\n```\n\nTemplate type parameter deduction with lvalues and rvalues:\n```c++\n// Since C++14 or later:\nvoid f(auto\u0026\u0026 t) {\n  // ...\n}\n\n// Since C++11 or later:\ntemplate \u003ctypename T\u003e\nvoid f(T\u0026\u0026 t) {\n  // ...\n}\n\nint x = 0;\nf(0); // T is int, deduces as f(int \u0026\u0026) =\u003e f(int\u0026\u0026)\nf(x); // T is int\u0026, deduces as f(int\u0026 \u0026\u0026) =\u003e f(int\u0026)\n\nint\u0026 y = x;\nf(y); // T is int\u0026, deduces as f(int\u0026 \u0026\u0026) =\u003e f(int\u0026)\n\nint\u0026\u0026 z = 0; // NOTE: `z` is an lvalue with type `int\u0026\u0026`.\nf(z); // T is int\u0026, deduces as f(int\u0026 \u0026\u0026) =\u003e f(int\u0026)\nf(std::move(z)); // T is int, deduces as f(int \u0026\u0026) =\u003e f(int\u0026\u0026)\n```\n\nSee also: [`std::move`](#stdmove), [`std::forward`](#stdforward), [`rvalue references`](#rvalue-references).\n\n### Variadic templates\nThe `...` syntax creates a _parameter pack_ or expands one. A template _parameter pack_ is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A template with at least one parameter pack is called a _variadic template_.\n```c++\ntemplate \u003ctypename... T\u003e\nstruct arity {\n  constexpr static int value = sizeof...(T);\n};\nstatic_assert(arity\u003c\u003e::value == 0);\nstatic_assert(arity\u003cchar, short, int\u003e::value == 3);\n```\n\nAn interesting use for this is creating an _initializer list_ from a _parameter pack_ in order to iterate over variadic function arguments.\n```c++\ntemplate \u003ctypename First, typename... Args\u003e\nauto sum(const First first, const Args... args) -\u003e decltype(first) {\n  const auto values = {first, args...};\n  return std::accumulate(values.begin(), values.end(), First{0});\n}\n\nsum(1, 2, 3, 4, 5); // 15\nsum(1, 2, 3);       // 6\nsum(1.5, 2.0, 3.7); // 7.2\n```\n\n### Initializer lists\nA lightweight array-like container of elements created using a \"braced list\" syntax. For example, `{ 1, 2, 3 }` creates a sequences of integers, that has type `std::initializer_list\u003cint\u003e`. Useful as a replacement to passing a vector of objects to a function.\n```c++\nint sum(const std::initializer_list\u003cint\u003e\u0026 list) {\n  int total = 0;\n  for (auto\u0026 e : list) {\n    total += e;\n  }\n\n  return total;\n}\n\nauto list = {1, 2, 3};\nsum(list); // == 6\nsum({1, 2, 3}); // == 6\nsum({}); // == 0\n```\n\n### Static assertions\nAssertions that are evaluated at compile-time.\n```c++\nconstexpr int x = 0;\nconstexpr int y = 1;\nstatic_assert(x == y, \"x != y\");\n```\n\n### auto\n`auto`-typed variables are deduced by the compiler according to the type of their initializer.\n```c++\nauto a = 3.14; // double\nauto b = 1; // int\nauto\u0026 c = b; // int\u0026\nauto d = { 0 }; // std::initializer_list\u003cint\u003e\nauto\u0026\u0026 e = 1; // int\u0026\u0026\nauto\u0026\u0026 f = b; // int\u0026\nauto g = new auto(123); // int*\nconst auto h = 1; // const int\nauto i = 1, j = 2, k = 3; // int, int, int\nauto l = 1, m = true, n = 1.61; // error -- `l` deduced to be int, `m` is bool\nauto o; // error -- `o` requires initializer\n```\n\nExtremely useful for readability, especially for complicated types:\n```c++\nstd::vector\u003cint\u003e v = ...;\nstd::vector\u003cint\u003e::const_iterator cit = v.cbegin();\n// vs.\nauto cit = v.cbegin();\n```\n\nFunctions can also deduce the return type using `auto`. In C++11, a return type must be specified either explicitly, or using `decltype` like so:\n```c++\ntemplate \u003ctypename X, typename Y\u003e\nauto add(X x, Y y) -\u003e decltype(x + y) {\n  return x + y;\n}\nadd(1, 2); // == 3\nadd(1, 2.0); // == 3.0\nadd(1.5, 1.5); // == 3.0\n```\nThe trailing return type in the above example is the _declared type_ (see section on [`decltype`](#decltype)) of the expression `x + y`. For example, if `x` is an integer and `y` is a double, `decltype(x + y)` is a double. Therefore, the above function will deduce the type depending on what type the expression `x + y` yields. Notice that the trailing return type has access to its parameters, and `this` when appropriate.\n\n### Lambda expressions\nA `lambda` is an unnamed function object capable of capturing variables in scope. It features: a _capture list_; an optional set of parameters with an optional trailing return type; and a body. Examples of capture lists:\n* `[]` - captures nothing.\n* `[=]` - capture local objects (local variables, parameters) in scope by value.\n* `[\u0026]` - capture local objects (local variables, parameters) in scope by reference.\n* `[this]` - capture `this` by reference.\n* `[a, \u0026b]` - capture objects `a` by value, `b` by reference.\n\n```c++\nint x = 1;\n\nauto getX = [=] { return x; };\ngetX(); // == 1\n\nauto addX = [=](int y) { return x + y; };\naddX(1); // == 2\n\nauto getXRef = [\u0026]() -\u003e int\u0026 { return x; };\ngetXRef(); // int\u0026 to `x`\n```\nBy default, value-captures cannot be modified inside the lambda because the compiler-generated method is marked as `const`. The `mutable` keyword allows modifying captured variables. The keyword is placed after the parameter-list (which must be present even if it is empty).\n```c++\nint x = 1;\n\nauto f1 = [\u0026x] { x = 2; }; // OK: x is a reference and modifies the original\n\nauto f2 = [x] { x = 2; }; // ERROR: the lambda can only perform const-operations on the captured value\n// vs.\nauto f3 = [x]() mutable { x = 2; }; // OK: the lambda can perform any operations on the captured value\n```\n\n### decltype\n`decltype` is an operator which returns the _declared type_ of an expression passed to it. cv-qualifiers and references are maintained if they are part of the expression. Examples of `decltype`:\n```c++\nint a = 1; // `a` is declared as type `int`\ndecltype(a) b = a; // `decltype(a)` is `int`\nconst int\u0026 c = a; // `c` is declared as type `const int\u0026`\ndecltype(c) d = a; // `decltype(c)` is `const int\u0026`\ndecltype(123) e = 123; // `decltype(123)` is `int`\nint\u0026\u0026 f = 1; // `f` is declared as type `int\u0026\u0026`\ndecltype(f) g = 1; // `decltype(f) is `int\u0026\u0026`\ndecltype((a)) h = g; // `decltype((a))` is int\u0026\n```\n```c++\ntemplate \u003ctypename X, typename Y\u003e\nauto add(X x, Y y) -\u003e decltype(x + y) {\n  return x + y;\n}\nadd(1, 2.0); // `decltype(x + y)` =\u003e `decltype(3.0)` =\u003e `double`\n```\n\nSee also: [`decltype(auto) (C++14)`](#decltypeauto).\n\n### Type aliases\nSemantically similar to using a `typedef` however, type aliases with `using` are easier to read and are compatible with templates.\n```c++\ntemplate \u003ctypename T\u003e\nusing Vec = std::vector\u003cT\u003e;\nVec\u003cint\u003e v; // std::vector\u003cint\u003e\n\nusing String = std::string;\nString s {\"foo\"};\n```\n\n### nullptr\nC++11 introduces a new null pointer type designed to replace C's `NULL` macro. `nullptr` itself is of type `std::nullptr_t` and can be implicitly converted into pointer types, and unlike `NULL`, not convertible to integral types except `bool`.\n```c++\nvoid foo(int);\nvoid foo(char*);\nfoo(NULL); // error -- ambiguous\nfoo(nullptr); // calls foo(char*)\n```\n\n### Strongly-typed enums\nType-safe enums that solve a variety of problems with C-style enums including: implicit conversions, inability to specify the underlying type, scope pollution.\n```c++\n// Specifying underlying type as `unsigned int`\nenum class Color : unsigned int { Red = 0xff0000, Green = 0xff00, Blue = 0xff };\n// `Red`/`Green` in `Alert` don't conflict with `Color`\nenum class Alert : bool { Red, Green };\nColor c = Color::Red;\n```\n\n### Attributes\nAttributes provide a universal syntax over `__attribute__(...)`, `__declspec`, etc.\n```c++\n// `noreturn` attribute indicates `f` doesn't return.\n[[ noreturn ]] void f() {\n  throw \"error\";\n}\n```\n\n### constexpr\nConstant expressions are expressions that are *possibly* evaluated by the compiler at compile-time. Only non-complex computations can be carried out in a constant expression (these rules are progressively relaxed in later versions). Use the `constexpr` specifier to indicate the variable, function, etc. is a constant expression.\n```c++\nconstexpr int square(int x) {\n  return x * x;\n}\n\nint square2(int x) {\n  return x * x;\n}\n\nint a = square(2);  // mov DWORD PTR [rbp-4], 4\n\nint b = square2(2); // mov edi, 2\n                    // call square2(int)\n                    // mov DWORD PTR [rbp-8], eax\n```\nIn the previous snippet, notice that the computation when calling `square` is carried out at compile-time, and then the result is embedded in the code generation, while `square2` is called at run-time.\n\n`constexpr` values are those that the compiler can evaluate, but are not guaranteed to, at compile-time:\n```c++\nconst int x = 123;\nconstexpr const int\u0026 y = x; // error -- constexpr variable `y` must be initialized by a constant expression\n```\n\nConstant expressions with classes:\n```c++\nstruct Complex {\n  constexpr Complex(double r, double i) : re{r}, im{i} { }\n  constexpr double real() { return re; }\n  constexpr double imag() { return im; }\n\nprivate:\n  double re;\n  double im;\n};\n\nconstexpr Complex I(0, 1);\n```\n\n### Delegating constructors\nConstructors can now call other constructors in the same class using an initializer list.\n```c++\nstruct Foo {\n  int foo;\n  Foo(int foo) : foo{foo} {}\n  Foo() : Foo(0) {}\n};\n\nFoo foo;\nfoo.foo; // == 0\n```\n\n### User-defined literals\nUser-defined literals allow you to extend the language and add your own syntax. To create a literal, define a `T operator \"\" X(...) { ... }` function that returns a type `T`, with a name `X`. Note that the name of this function defines the name of the literal. Any literal names not starting with an underscore are reserved and won't be invoked. There are rules on what parameters a user-defined literal function should accept, according to what type the literal is called on.\n\nConverting Celsius to Fahrenheit:\n```c++\n// `unsigned long long` parameter required for integer literal.\nlong long operator \"\" _celsius(unsigned long long tempCelsius) {\n  return std::llround(tempCelsius * 1.8 + 32);\n}\n24_celsius; // == 75\n```\n\nString to integer conversion:\n```c++\n// `const char*` and `std::size_t` required as parameters.\nint operator \"\" _int(const char* str, std::size_t) {\n  return std::stoi(str);\n}\n\n\"123\"_int; // == 123, with type `int`\n```\n\n### Explicit virtual overrides\nSpecifies that a virtual function overrides another virtual function. If the virtual function does not override a parent's virtual function, throws a compiler error.\n```c++\nstruct A {\n  virtual void foo();\n  void bar();\n};\n\nstruct B : A {\n  void foo() override; // correct -- B::foo overrides A::foo\n  void bar() override; // error -- A::bar is not virtual\n  void baz() override; // error -- B::baz does not override A::baz\n};\n```\n\n### Final specifier\nSpecifies that a virtual function cannot be overridden in a derived class or that a class cannot be inherited from.\n```c++\nstruct A {\n  virtual void foo();\n};\n\nstruct B : A {\n  virtual void foo() final;\n};\n\nstruct C : B {\n  virtual void foo(); // error -- declaration of 'foo' overrides a 'final' function\n};\n```\n\nClass cannot be inherited from.\n```c++\nstruct A final {};\nstruct B : A {}; // error -- base 'A' is marked 'final'\n```\n\n### Default functions\nA more elegant, efficient way to provide a default implementation of a function, such as a constructor.\n```c++\nstruct A {\n  A() = default;\n  A(int x) : x{x} {}\n  int x {1};\n};\nA a; // a.x == 1\nA a2 {123}; // a.x == 123\n```\n\nWith inheritance:\n```c++\nstruct B {\n  B() : x{1} {}\n  int x;\n};\n\nstruct C : B {\n  // Calls B::B\n  C() = default;\n};\n\nC c; // c.x == 1\n```\n\n### Deleted functions\nA more elegant, efficient way to provide a deleted implementation of a function. Useful for preventing copies on objects.\n```c++\nclass A {\n  int x;\n\npublic:\n  A(int x) : x{x} {};\n  A(const A\u0026) = delete;\n  A\u0026 operator=(const A\u0026) = delete;\n};\n\nA x {123};\nA y = x; // error -- call to deleted copy constructor\ny = x; // error -- operator= deleted\n```\n\n### Range-based for loops\nSyntactic sugar for iterating over a container's elements.\n```c++\nstd::array\u003cint, 5\u003e a {1, 2, 3, 4, 5};\nfor (int\u0026 x : a) x *= 2;\n// a == { 2, 4, 6, 8, 10 }\n```\n\nNote the difference when using `int` as opposed to `int\u0026`:\n```c++\nstd::array\u003cint, 5\u003e a {1, 2, 3, 4, 5};\nfor (int x : a) x *= 2;\n// a == { 1, 2, 3, 4, 5 }\n```\n\n### Special member functions for move semantics\nThe copy constructor and copy assignment operator are called when copies are made, and with C++11's introduction of move semantics, there is now a move constructor and move assignment operator for moves.\n```c++\nstruct A {\n  std::string s;\n  A() : s{\"test\"} {}\n  A(const A\u0026 o) : s{o.s} {}\n  A(A\u0026\u0026 o) : s{std::move(o.s)} {}\n  A\u0026 operator=(A\u0026\u0026 o) {\n   s = std::move(o.s);\n   return *this;\n  }\n};\n\nA f(A a) {\n  return a;\n}\n\nA a1 = f(A{}); // move-constructed from rvalue temporary\nA a2 = std::move(a1); // move-constructed using std::move\nA a3 = A{};\na2 = std::move(a3); // move-assignment using std::move\na1 = f(A{}); // move-assignment from rvalue temporary\n```\n\n### Converting constructors\nConverting constructors will convert values of braced list syntax into constructor arguments.\n```c++\nstruct A {\n  A(int) {}\n  A(int, int) {}\n  A(int, int, int) {}\n};\n\nA a {0, 0}; // calls A::A(int, int)\nA b(0, 0); // calls A::A(int, int)\nA c = {0, 0}; // calls A::A(int, int)\nA d {0, 0, 0}; // calls A::A(int, int, int)\n```\n\nNote that the braced list syntax does not allow narrowing:\n```c++\nstruct A {\n  A(int) {}\n};\n\nA a(1.1); // OK\nA b {1.1}; // Error narrowing conversion from double to int\n```\n\nNote that if a constructor accepts a `std::initializer_list`, it will be called instead:\n```c++\nstruct A {\n  A(int) {}\n  A(int, int) {}\n  A(int, int, int) {}\n  A(std::initializer_list\u003cint\u003e) {}\n};\n\nA a {0, 0}; // calls A::A(std::initializer_list\u003cint\u003e)\nA b(0, 0); // calls A::A(int, int)\nA c = {0, 0}; // calls A::A(std::initializer_list\u003cint\u003e)\nA d {0, 0, 0}; // calls A::A(std::initializer_list\u003cint\u003e)\n```\n\n### Explicit conversion functions\nConversion functions can now be made explicit using the `explicit` specifier.\n```c++\nstruct A {\n  operator bool() const { return true; }\n};\n\nstruct B {\n  explicit operator bool() const { return true; }\n};\n\nA a;\nif (a); // OK calls A::operator bool()\nbool ba = a; // OK copy-initialization selects A::operator bool()\n\nB b;\nif (b); // OK calls B::operator bool()\nbool bb = b; // error copy-initialization does not consider B::operator bool()\n```\n### Inline namespaces\nAll members of an inline namespace are treated as if they were part of its parent namespace, allowing specialization of functions and easing the process of versioning. This is a transitive property, if A contains B, which in turn contains C and both B and C are inline namespaces, C's members can be used as if they were on A.\n\n```c++\nnamespace Program {\n  namespace Version1 {\n    int getVersion() { return 1; }\n    bool isFirstVersion() { return true; }\n  }\n  inline namespace Version2 {\n    int getVersion() { return 2; }\n  }\n}\n\nint version {Program::getVersion()};              // Uses getVersion() from Version2\nint oldVersion {Program::Version1::getVersion()}; // Uses getVersion() from Version1\nbool firstVersion {Program::isFirstVersion()};    // Does not compile when Version2 is added\n```\n\n### Non-static data member initializers\nAllows non-static data members to be initialized where they are declared, potentially cleaning up constructors of default initializations.\n\n```c++\n// Default initialization prior to C++11\nclass Human {\n    Human() : age{0} {}\n  private:\n    unsigned age;\n};\n// Default initialization on C++11\nclass Human {\n  private:\n    unsigned age {0};\n};\n```\n\n### Right angle brackets\nC++11 is now able to infer when a series of right angle brackets is used as an operator or as a closing statement of typedef, without having to add whitespace.\n\n```c++\ntypedef std::map\u003cint, std::map \u003cint, std::map \u003cint, int\u003e \u003e \u003e cpp98LongTypedef;\ntypedef std::map\u003cint, std::map \u003cint, std::map \u003cint, int\u003e\u003e\u003e   cpp11LongTypedef;\n```\n\n### Ref-qualified member functions\nMember functions can now be qualified depending on whether `*this` is an lvalue or rvalue reference.\n\n```c++\nstruct Bar {\n  // ...\n};\n\nstruct Foo {\n  Bar\u0026 getBar() \u0026 { return bar; }\n  const Bar\u0026 getBar() const\u0026 { return bar; }\n  Bar\u0026\u0026 getBar() \u0026\u0026 { return std::move(bar); }\n  const Bar\u0026\u0026 getBar() const\u0026\u0026 { return std::move(bar); }\nprivate:\n  Bar bar;\n};\n\nFoo foo{};\nBar bar = foo.getBar(); // calls `Bar\u0026 getBar() \u0026`\n\nconst Foo foo2{};\nBar bar2 = foo2.getBar(); // calls `Bar\u0026 Foo::getBar() const\u0026`\n\nFoo{}.getBar(); // calls `Bar\u0026\u0026 Foo::getBar() \u0026\u0026`\nstd::move(foo).getBar(); // calls `Bar\u0026\u0026 Foo::getBar() \u0026\u0026`\nstd::move(foo2).getBar(); // calls `const Bar\u0026\u0026 Foo::getBar() const\u0026`\n```\n\n### Trailing return types\nC++11 allows functions and lambdas an alternative syntax for specifying their return types.\n```c++\nint f() {\n  return 123;\n}\n// vs.\nauto f() -\u003e int {\n  return 123;\n}\n```\n```c++\nauto g = []() -\u003e int {\n  return 123;\n};\n```\nThis feature is especially useful when certain return types cannot be resolved:\n```c++\n// NOTE: This does not compile!\ntemplate \u003ctypename T, typename U\u003e\ndecltype(a + b) add(T a, U b) {\n    return a + b;\n}\n\n// Trailing return types allows this:\ntemplate \u003ctypename T, typename U\u003e\nauto add(T a, U b) -\u003e decltype(a + b) {\n    return a + b;\n}\n```\nIn C++14, [`decltype(auto) (C++14)`](#decltypeauto) can be used instead.\n\n### Noexcept specifier\nThe `noexcept` specifier specifies whether a function could throw exceptions. It is an improved version of `throw()`.\n\n```c++\nvoid func1() noexcept;        // does not throw\nvoid func2() noexcept(true);  // does not throw\nvoid func3() throw();         // does not throw\n\nvoid func4() noexcept(false); // may throw\n```\n\nNon-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function std::terminate is called.\n\n```c++\nextern void f();  // potentially-throwing\nvoid g() noexcept {\n    f();          // valid, even if f throws\n    throw 42;     // valid, effectively a call to std::terminate\n}\n```\n\n### char32_t and char16_t\nProvides standard types for representing UTF-8 strings.\n```c++\nchar32_t utf8_str[] = U\"\\u0123\";\nchar16_t utf8_str[] = u\"\\u0123\";\n```\n\n### Raw string literals\nC++11 introduces a new way to declare string literals as \"raw string literals\". Characters issued from an escape sequence (tabs, line feeds, single backslashes, etc.) can be inputted raw while preserving formatting. This is useful, for example, to write literary text, which might contain a lot of quotes or special formatting. This can make your string literals easier to read and maintain.\n\nA raw string literal is declared using the following syntax:\n```\nR\"delimiter(raw_characters)delimiter\"\n```\nwhere:\n* `delimiter` is an optional sequence of characters made of any source character except parentheses, backslashes and spaces.\n* `raw_characters` is any raw character sequence; must not contain the closing sequence `\")delimiter\"`.\n\nExample:\n```cpp\n// msg1 and msg2 are equivalent.\nconst char* msg1 = \"\\nHello,\\n\\tworld!\\n\";\nconst char* msg2 = R\"(\nHello,\n\tworld!\n)\";\n```\n\n## C++11 Library Features\n\n### std::move\n`std::move` indicates that the object passed to it may have its resources transferred. Using objects that have been moved from should be used with care, as they can be left in an unspecified state (see: [What can I do with a moved-from object?](http://stackoverflow.com/questions/7027523/what-can-i-do-with-a-moved-from-object)).\n\nA definition of `std::move` (performing a move is nothing more than casting to an rvalue reference):\n```c++\ntemplate \u003ctypename T\u003e\ntypename remove_reference\u003cT\u003e::type\u0026\u0026 move(T\u0026\u0026 arg) {\n  return static_cast\u003ctypename remove_reference\u003cT\u003e::type\u0026\u0026\u003e(arg);\n}\n```\n\nTransferring `std::unique_ptr`s:\n```c++\nstd::unique_ptr\u003cint\u003e p1 {new int{0}};  // in practice, use std::make_unique\nstd::unique_ptr\u003cint\u003e p2 = p1; // error -- cannot copy unique pointers\nstd::unique_ptr\u003cint\u003e p3 = std::move(p1); // move `p1` into `p3`\n                                         // now unsafe to dereference object held by `p1`\n```\n\n### std::forward\nReturns the arguments passed to it while maintaining their value category and cv-qualifiers. Useful for generic code and factories. Used in conjunction with [`forwarding references`](#forwarding-references).\n\nA definition of `std::forward`:\n```c++\ntemplate \u003ctypename T\u003e\nT\u0026\u0026 forward(typename remove_reference\u003cT\u003e::type\u0026 arg) {\n  return static_cast\u003cT\u0026\u0026\u003e(arg);\n}\n```\n\nAn example of a function `wrapper` which just forwards other `A` objects to a new `A` object's copy or move constructor:\n```c++\nstruct A {\n  A() = default;\n  A(const A\u0026 o) { std::cout \u003c\u003c \"copied\" \u003c\u003c std::endl; }\n  A(A\u0026\u0026 o) { std::cout \u003c\u003c \"moved\" \u003c\u003c std::endl; }\n};\n\ntemplate \u003ctypename T\u003e\nA wrapper(T\u0026\u0026 arg) {\n  return A{std::forward\u003cT\u003e(arg)};\n}\n\nwrapper(A{}); // moved\nA a;\nwrapper(a); // copied\nwrapper(std::move(a)); // moved\n```\n\nSee also: [`forwarding references`](#forwarding-references), [`rvalue references`](#rvalue-references).\n\n### std::thread\nThe `std::thread` library provides a standard way to control threads, such as spawning and killing them. In the example below, multiple threads are spawned to do different calculations and then the program waits for all of them to finish.\n\n```c++\nvoid foo(bool clause) { /* do something... */ }\n\nstd::vector\u003cstd::thread\u003e threadsVector;\nthreadsVector.emplace_back([]() {\n  // Lambda function that will be invoked\n});\nthreadsVector.emplace_back(foo, true);  // thread will run foo(true)\nfor (auto\u0026 thread : threadsVector) {\n  thread.join(); // Wait for threads to finish\n}\n```\n\n### std::to_string\nConverts a numeric argument to a `std::string`.\n```c++\nstd::to_string(1.2); // == \"1.2\"\nstd::to_string(123); // == \"123\"\n```\n\n### Type traits\nType traits defines a compile-time template-based interface to query or modify the properties of types.\n```c++\nstatic_assert(std::is_integral\u003cint\u003e::value);\nstatic_assert(std::is_same\u003cint, int\u003e::value);\nstatic_assert(std::is_same\u003cstd::conditional\u003ctrue, int, double\u003e::type, int\u003e::value);\n```\n\n### Smart pointers\nC++11 introduces new smart pointers: `std::unique_ptr`, `std::shared_ptr`, `std::weak_ptr`. `std::auto_ptr` now becomes deprecated and then eventually removed in C++17.\n\n`std::unique_ptr` is a non-copyable, movable pointer that manages its own heap-allocated memory. **Note: Prefer using the `std::make_X` helper functions as opposed to using constructors. See the sections for [std::make_unique](https://github.com/AnthonyCalandra/modern-cpp-features/blob/master/CPP14.md#stdmake_unique) and [std::make_shared](#stdmake_shared).**\n```c++\nstd::unique_ptr\u003cFoo\u003e p1 { new Foo{} };  // `p1` owns `Foo`\nif (p1) {\n  p1-\u003ebar();\n}\n\n{\n  std::unique_ptr\u003cFoo\u003e p2 {std::move(p1)};  // Now `p2` owns `Foo`\n  f(*p2);\n\n  p1 = std::move(p2);  // Ownership returns to `p1` -- `p2` gets destroyed\n}\n\nif (p1) {\n  p1-\u003ebar();\n}\n// `Foo` instance is destroyed when `p1` goes out of scope\n```\n\nA `std::shared_ptr` is a smart pointer that manages a resource that is shared across multiple owners. A shared pointer holds a _control block_ which has a few components such as the managed object and a reference counter. All control block access is thread-safe, however, manipulating the managed object itself is *not* thread-safe.\n```c++\nvoid foo(std::shared_ptr\u003cT\u003e t) {\n  // Do something with `t`...\n}\n\nvoid bar(std::shared_ptr\u003cT\u003e t) {\n  // Do something with `t`...\n}\n\nvoid baz(std::shared_ptr\u003cT\u003e t) {\n  // Do something with `t`...\n}\n\nstd::shared_ptr\u003cT\u003e p1 {new T{}};\n// Perhaps these take place in another threads?\nfoo(p1);\nbar(p1);\nbaz(p1);\n```\n\n### std::chrono\nThe chrono library contains a set of utility functions and types that deal with _durations_, _clocks_, and _time points_. One use case of this library is benchmarking code:\n```c++\nstd::chrono::time_point\u003cstd::chrono::steady_clock\u003e start, end;\nstart = std::chrono::steady_clock::now();\n// Some computations...\nend = std::chrono::steady_clock::now();\n\nstd::chrono::duration\u003cdouble\u003e elapsed_seconds = end - start;\ndouble t = elapsed_seconds.count(); // t number of seconds, represented as a `double`\n```\n\n### Tuples\nTuples are a fixed-size collection of heterogeneous values. Access the elements of a `std::tuple` by unpacking using [`std::tie`](#stdtie), or using `std::get`.\n```c++\n// `playerProfile` has type `std::tuple\u003cint, const char*, const char*\u003e`.\nauto playerProfile = std::make_tuple(51, \"Frans Nielsen\", \"NYI\");\nstd::get\u003c0\u003e(playerProfile); // 51\nstd::get\u003c1\u003e(playerProfile); // \"Frans Nielsen\"\nstd::get\u003c2\u003e(playerProfile); // \"NYI\"\n```\n\n### std::tie\nCreates a tuple of lvalue references. Useful for unpacking `std::pair` and `std::tuple` objects. Use `std::ignore` as a placeholder for ignored values. In C++17, structured bindings should be used instead.\n```c++\n// With tuples...\nstd::string playerName;\nstd::tie(std::ignore, playerName, std::ignore) = std::make_tuple(91, \"John Tavares\", \"NYI\");\n\n// With pairs...\nstd::string yes, no;\nstd::tie(yes, no) = std::make_pair(\"yes\", \"no\");\n```\n\n### std::array\n`std::array` is a container built on top of a C-style array. Supports common container operations such as sorting.\n```c++\nstd::array\u003cint, 3\u003e a = {2, 1, 3};\nstd::sort(a.begin(), a.end()); // a == { 1, 2, 3 }\nfor (int\u0026 x : a) x *= 2; // a == { 2, 4, 6 }\n```\n\n### Unordered containers\nThese containers maintain average constant-time complexity for search, insert, and remove operations. In order to achieve constant-time complexity, sacrifices order for speed by hashing elements into buckets. There are four unordered containers:\n* `unordered_set`\n* `unordered_multiset`\n* `unordered_map`\n* `unordered_multimap`\n\n### std::make_shared\n`std::make_shared` is the recommended way to create instances of `std::shared_ptr`s due to the following reasons:\n* Avoid having to use the `new` operator.\n* Prevents code repetition when specifying the underlying type the pointer shall hold.\n* It provides exception-safety. Suppose we were calling a function `foo` like so:\n```c++\nfoo(std::shared_ptr\u003cT\u003e{new T{}}, function_that_throws(), std::shared_ptr\u003cT\u003e{new T{}});\n```\nThe compiler is free to call `new T{}`, then `function_that_throws()`, and so on... Since we have allocated data on the heap in the first construction of a `T`, we have introduced a leak here. With `std::make_shared`, we are given exception-safety:\n```c++\nfoo(std::make_shared\u003cT\u003e(), function_that_throws(), std::make_shared\u003cT\u003e());\n```\n* Prevents having to do two allocations. When calling `std::shared_ptr{ new T{} }`, we have to allocate memory for `T`, then in the shared pointer we have to allocate memory for the control block within the pointer.\n\nSee the section on [smart pointers](#smart-pointers) for more information on `std::unique_ptr` and `std::shared_ptr`.\n\n### std::ref\n`std::ref(val)` is used to create object of type `std::reference_wrapper` that holds reference of val. Used in cases when usual reference passing using `\u0026` does not compile or `\u0026` is dropped due to type deduction. `std::cref` is similar but created reference wrapper holds a const reference to val.\n\n```c++\n// create a container to store reference of objects.\nauto val = 99;\nauto _ref = std::ref(val);\n_ref++;\nauto _cref = std::cref(val);\n//_cref++; does not compile\nstd::vector\u003cstd::reference_wrapper\u003cint\u003e\u003evec; // vector\u003cint\u0026\u003evec does not compile\nvec.push_back(_ref); // vec.push_back(\u0026i) does not compile\ncout \u003c\u003c val \u003c\u003c endl; // prints 100\ncout \u003c\u003c vec[0] \u003c\u003c endl; // prints 100\ncout \u003c\u003c _cref; // prints 100\n```\n\n### Memory model\nC++11 introduces a memory model for C++, which means library support for threading and atomic operations. Some of these operations include (but aren't limited to) atomic loads/stores, compare-and-swap, atomic flags, promises, futures, locks, and condition variables.\n\nSee the sections on: [std::thread](#stdthread)\n\n### std::async\n`std::async` runs the given function either asynchronously or lazily-evaluated, then returns a `std::future` which holds the result of that function call.\n\nThe first parameter is the policy which can be:\n1. `std::launch::async | std::launch::deferred` It is up to the implementation whether to perform asynchronous execution or lazy evaluation.\n1. `std::launch::async` Run the callable object on a new thread.\n1. `std::launch::deferred` Perform lazy evaluation on the current thread.\n\n```c++\nint foo() {\n  /* Do something here, then return the result. */\n  return 1000;\n}\n\nauto handle = std::async(std::launch::async, foo);  // create an async task\nauto result = handle.get();  // wait for the result\n```\n\n### std::begin/end\n`std::begin` and `std::end` free functions were added to return begin and end iterators of a container generically. These functions also work with raw arrays which do not have `begin` and `end` member functions.\n\n```c++\ntemplate \u003ctypename T\u003e\nint CountTwos(const T\u0026 container) {\n  return std::count_if(std::begin(container), std::end(container), [](int item) {\n    return item == 2;\n  });\n}\n\nstd::vector\u003cint\u003e vec = {2, 2, 43, 435, 4543, 534};\nint arr[8] = {2, 43, 45, 435, 32, 32, 32, 32};\nauto a = CountTwos(vec); // 2\nauto b = CountTwos(arr);  // 1\n```\n\n\n\n## Acknowledgements\n* [cppreference](http://en.cppreference.com/w/cpp) - especially useful for finding examples and documentation of new library features.\n* [C++ Rvalue References Explained](http://web.archive.org/web/20240324121501/http://thbecker.net/articles/rvalue_references/section_01.html) - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics.\n* [clang](http://clang.llvm.org/cxx_status.html) and [gcc](https://gcc.gnu.org/projects/cxx-status.html)'s standards support pages. Also included here are the proposals for language/library features that I used to help find a description of, what it's meant to fix, and some examples.\n* [Compiler explorer](https://godbolt.org/)\n* [Scott Meyers' Effective Modern C++](https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996) - highly recommended series of books!\n* [Jason Turner's C++ Weekly](https://www.youtube.com/channel/UCxHAlbZQNFU2LgEtiqd2Maw) - nice collection of C++-related videos.\n* [What can I do with a moved-from object?](http://stackoverflow.com/questions/7027523/what-can-i-do-with-a-moved-from-object)\n* [What are some uses of decltype(auto)?](http://stackoverflow.com/questions/24109737/what-are-some-uses-of-decltypeauto)\n\n## Author\nAnthony Calandra\n\n## Content Contributors\nSee: https://github.com/AnthonyCalandra/modern-cpp-features/graphs/contributors\n\n## License\nMIT\n","funding_links":[],"categories":["GPU computing","Others","Articles","Programming Language Tutorials","Cheatsheet速查表","Python","C/C++ 程序设计","C++","ETC","**Code**","Libraries","C/C++生态圈Dev\u0026Ops工具与服务","Unknown","Uncategorized"],"sub_categories":["C++/C","网络服务_其他","C++ References / Guidelines","C++","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAnthonyCalandra%2Fmodern-cpp-features","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAnthonyCalandra%2Fmodern-cpp-features","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAnthonyCalandra%2Fmodern-cpp-features/lists"}