### Example of std::map Deduction Guides Usage Source: https://devdocs.io/cpp/container/map/deduction_guides This C++ example demonstrates the usage of `std::map` deduction guides. It shows how to initialize a map using an initializer list (guide #2) and from an iterator range (guide #1), highlighting a common pitfall with braced-init-lists. ```cpp #include int main() { // std::map m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type; cannot deduce // pair from {"foo", 1} or {"bar", 2} std::map m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::map m2(m1.begin(), m1.end()); // guide #1 } ``` -------------------------------- ### C++ Example: Using std::set Deduction Guides Source: https://devdocs.io/cpp/container/set/deduction_guides A simple C++ example demonstrating the usage of `std::set` deduction guides. It shows how to initialize a `std::set` directly from an initializer list (guide #2) and from an iterator range (guide #1), with the compiler deducing the set's type. ```cpp #include int main() { // guide #2 deduces std::set std::set s = {1, 2, 3, 4}; // guide #1 deduces std::set std::set s2(s.begin(), s.end()); } ``` -------------------------------- ### C++ std::basic_string Deduction Guide Example Source: https://devdocs.io/cpp/string/basic_string/deduction_guides Demonstrates the usage of deduction guides for std::basic_string, showcasing initialization from a vector of characters and using range-based deduction with C++23 features. ```cpp #include #include #include int main() { std::vector v = {'a', 'b', 'c'}; std::basic_string s1(v.begin(), v.end()); // uses deduction guide (1) assert(s1 == "abc"); #if __cpp_lib_containers_ranges >= 202202L std::vector v4{0x43, 43, 053, 0x32, 0x33}; std::basic_string s4(std::from_range, v4); // uses deduction guide (4) assert(s4 == L"C++23"); #endif } ``` -------------------------------- ### Example of using std::multimap deduction guides Source: https://devdocs.io/cpp/container/multimap/deduction_guides Demonstrates how to use deduction guides for std::multimap construction with initializer lists and iterator ranges. Highlights the corrected syntax for initializer lists to enable type deduction. ```cpp #include int main() { // std::multimap m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type; cannot deduce // pair from {"foo", 1} or {"bar", 2} std::multimap m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::multimap m2(m1.begin(), m1.end()); // guide #1 } ``` -------------------------------- ### C++ Value-Initialization Syntax Examples Source: https://devdocs.io/cpp/language/value_initialization Illustrates the various syntaxes used to perform value-initialization in C++. ```C++ T (); new T (); Class::Class(...) : member() { ... } T object {}; T {}; new T {}; Class::Class(...) : member{} { ... } ``` -------------------------------- ### C++ Example: Using std::shared_ptr Deduction Guides Source: https://devdocs.io/cpp/memory/shared_ptr/deduction_guides This C++ example demonstrates the usage of explicit deduction guides for std::shared_ptr when initializing from std::weak_ptr. It highlights how these guides are invoked in specific scenarios. ```cpp #include int main() { auto p = std::make_shared(42); std::weak_ptr w{p}; // explicit deduction guide is used in this case std::shared_ptr p2{w}; // explicit deduction guide is used in this case } ``` -------------------------------- ### C++ Direct-Initialization Syntax Examples Source: https://devdocs.io/cpp/language/direct_initialization Demonstrates various syntaxes for direct initialization in C++, including initialization with constructor arguments and aggregate initialization. Supports features from C++11 onwards. ```cpp T object(arg); T object(arg1, arg2, ...); T object{arg}; // Since C++11 T(other) T(arg1, arg2, ...) static_cast(other) new T(args, ...) Class::Class() : member(args, ...) { ... } // Since C++11 [arg]() { ... } ``` -------------------------------- ### C++ Initialization Examples Source: https://devdocs.io/cpp/language/value_initialization Provides practical examples of various C++ initialization scenarios using `assert` and `std::cout`. It covers initialization of integers, doubles, pointers, custom structs with implicit and user-provided constructors, and standard containers like `std::vector`. ```cpp #include #include #include #include struct T1 { int mem1; std::string mem2; virtual void foo() {} }; struct T2 { int mem1; std::string mem2; T2(const T2&) {} }; struct T3 { int mem1; std::string mem2; T3() {} }; std::string s{}; int main() { int n{}; assert(n == 0); double f = double(); assert(f == 0.0); int* a = new int[10](); assert(a[9] == 0); T1 t1{}; assert(t1.mem1 == 0); assert(t1.mem2 == ""); T3 t3{}; std::cout << t3.mem1; assert(t3.mem2 == ""); std::vector v(3); assert(v[2] == 0); std::cout << '\n'; delete[] a; } ``` -------------------------------- ### C++ Example of std::tuple Deduction Guide Usage Source: https://devdocs.io/cpp/utility/tuple/deduction_guides An example demonstrating the use of an explicit deduction guide for std::tuple with an array of pointers. This showcases how std::tuple can deduce types from heterogeneous arrays, leveraging the deduction guides. ```cpp #include int main() { int a[2], b[3], c[4]; std::tuple t1{a, b, c}; // explicit deduction guide is used in this case } ``` -------------------------------- ### C++ Initialization Syntax Examples Source: https://devdocs.io/cpp/language/initialization Demonstrates the different syntaxes for providing initial values to variables in C++. These include using parentheses for expression lists, an equals sign for expression assignment, and curly braces for initializer lists or designated initializers. ```cpp int x(10); // Using parentheses int y = 20; // Using equals sign int z{30}; // Using curly braces (initializer list) struct Point { int x; int y; }; Point p = {1, 2}; // Aggregate initialization with initializer list Point q = {.x = 1, .y = 2}; // Designated initializer list (C++20) ``` -------------------------------- ### C++ Example: `std::list` Initialization with Deduction Guides Source: https://devdocs.io/cpp/container/list/deduction_guides This example demonstrates how to use `std::list` deduction guides in C++ to initialize a list from a `std::vector`'s iterators. It shows both explicit use of the deduction guide and implicit deduction. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::list std::list x(v.begin(), v.end()); // deduces std::list::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::list y{v.begin(), v.end()}; } ``` -------------------------------- ### C++ Constructor Initialization Example Source: https://devdocs.io/cpp/language/constructor Demonstrates the initialization order of base classes, members, and delegating constructors in C++. ```cpp #include #include #include struct Base { int n; }; struct Class : public Base { unsigned char x; unsigned char y; std::mutex m; std::lock_guard lg; std::fstream f; std::string s; Class(int x) : Base{123}, // initialize base class x(x), // x (member) is initialized with x (parameter) y{0}, // y initialized to 0 f{"test.cc", std::ios::app}, // this takes place after m and lg are initialized s(__func__), // __func__ is available because init-list is a part of constructor lg(m), // lg uses m, which is already initialized m{} // m is initialized before lg even though it appears last here {} Class(double a) : y(a + 1), x(y), // x will be initialized before y, its value here is indeterminate lg(m) {} Class() try : Class(0.0) // delegate constructor { // ... } catch (...) { // exception occurred on initialization } }; int main() { Class c; Class c1(1); Class c2(0.1); } ``` -------------------------------- ### C++ Nested Template Deduction Guide Example Source: https://devdocs.io/cpp/language/class_template_argument_deduction Illustrates deduction guides for nested template classes. This example uses `S::N` and shows how overload resolution selects the appropriate deduction guide when initializing a nested template instance with multiple arguments. ```cpp template struct S { template struct N { N(T); N(T, U); template N(V, U); }; }; S::N x{2.0, 1}; // the implicitly-generated deduction guides are (note that T is already known to be int) // F1: template // S::N F(int); // F2: template // S::N F(int, U); // F3: template // S::N F(V, U); // F4: template // S::N F(S::N); (copy deduction candidate) // Overload resolution for direct-list-init with "{2.0, 1}" as the initializer // chooses F3 with U=int and V=double. // The return type is S::N // result: // S::N x{2.0, 1}; ``` -------------------------------- ### C++ string reserve and capacity management example Source: https://devdocs.io/cpp/string/basic_string/reserve Demonstrates how to use std::string::reserve to pre-allocate storage and observes capacity growth. Includes usage of shrink_to_fit. This example requires the , , and headers. ```cpp #include #include #include int main() { std::string s; std::cout << "1) Initially: " << s.capacity() << '\n'; const std::string::size_type new_cap{101u}; s.reserve(new_cap); assert(s.capacity() >= new_cap); std::cout << "2) After reserve(" << new_cap << "): " << s.capacity() << '\n'; // observing the capacity growth factor auto cap{s.capacity()}; for (int check{}; check != 4; ++check) { while (cap == s.capacity()) s += '$'; cap = s.capacity(); std::cout << (3) + check << ") Capacity: " << cap << '\n'; } // s.reserve(); // deprecated/removed in C++20/26, use: s.shrink_to_fit(); std::cout << "7) After shrink_to_fit: " << s.capacity() << '\n'; } ``` -------------------------------- ### C++ Example: Using std::vector Deduction Guides Source: https://devdocs.io/cpp/container/vector/deduction_guides Demonstrates the usage of `std::vector` deduction guides in C++. The first example shows deduction from iterators, while the second highlights how list initialization might affect deduction behavior. ```cpp #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::vector std::vector x(v.begin(), v.end()); // deduces std::vector::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::vector y{v.begin(), v.end()}; } ``` -------------------------------- ### C++ Deferred Dynamic Initialization Example Source: https://devdocs.io/cpp/language/initialization Demonstrates deferred dynamic initialization across multiple translation units. The example highlights potential issues if initialization order is not carefully managed, especially when one object's constructor depends on another object that might not be initialized yet. ```cpp // ============ // == File 1 == #include "a.h" #include "b.h" B b; A::A() { b.Use(); } // ============ // == File 2 == #include "a.h" A a; // ============ // == File 3 == #include "a.h" #include "b.h" extern A a; extern B b; int main() { a.Use(); b.Use(); } // If a is initialized before main is entered, b may still be uninitialized // at the point where A::A() uses it (because dynamic initialization is // indeterminately sequenced across translation units) // If a is initialized at some point after the first statement of main (which odr-uses // a function defined in File 1, forcing its dynamic initialization to run), // then b will be initialized prior to its use in A::A ``` -------------------------------- ### std::queue Example Source: https://devdocs.io/cpp/container/queue Demonstrates the basic usage of std::queue, including push, front, back, pop, and size operations. It also shows how to iterate and empty the queue. ```cpp #include #include #include int main() { std::queue q; q.push(0); // back pushes 0 q.push(1); // q = 0 1 q.push(2); // q = 0 1 2 q.push(3); // q = 0 1 2 3 assert(q.front() == 0); assert(q.back() == 3); assert(q.size() == 4); q.pop(); // removes the front element, 0 assert(q.size() == 3); // Print and remove all elements. Note that std::queue does not // support begin()/end(), so a range-for-loop cannot be used. std::cout << "q: "; for (; !q.empty(); q.pop()) std::cout << q.front() << ' '; std::cout << '\n'; assert(q.size() == 0); } ``` -------------------------------- ### C++ Example: Constructing std::forward_list with Deduction Guides Source: https://devdocs.io/cpp/container/forward_list/deduction_guides This C++ example demonstrates how to use the deduction guides for std::forward_list. It shows constructing a forward_list 'x' from a std::vector's iterators using the C++17 deduction guide, and a forward_list 'y' using list-initialization which may involve a different overload resolution path. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::forward_list std::forward_list x(v.begin(), v.end()); // deduces std::forward_list::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::forward_list y{v.begin(), v.end()}; } ``` -------------------------------- ### C++ Unordered Set Deduction Guides Example Source: https://devdocs.io/cpp/container/unordered_set/deduction_guides Demonstrates the use of deduction guides for `std::unordered_set` in C++. This example shows how the compiler can deduce the type of the `unordered_set` based on initializer lists and iterator ranges. Requires C++20 or later for full support. ```cpp #include int main() { // guide #2 deduces std::unordered_set std::unordered_set s = {1, 2, 3, 4}; // guide #1 deduces std::unordered_set std::unordered_set s2(s.begin(), s.end()); } ``` -------------------------------- ### C++ Initialization Types Examples Source: https://devdocs.io/cpp/language/initialization Illustrates various types of initialization in C++: value, direct, copy, list, aggregate, and reference initialization. Each type is shown with a brief example to clarify its usage context. ```cpp #include void initialization_types() { std::string s{}; // Value initialization std::string t("hello"); // Direct initialization std::string u = "hello"; // Copy initialization std::string v{'a', 'b', 'c'}; // List initialization char a[3] = {'a', 'b'}; // Aggregate initialization char& c = a[0]; // Reference initialization } ``` -------------------------------- ### C++ Filesystem Path Construction Example Source: https://devdocs.io/cpp/filesystem/path/path Demonstrates the construction of std::filesystem::path objects using various string formats, including portable, native, UTF-32, and UTF-8. It shows how to print these paths to the console. This example requires the `` and `` headers. ```cpp #include #include namespace fs = std::filesystem; int main() { fs::path p1 = "/usr/lib/sendmail.cf"; // portable format fs::path p2 = "C:\\users\\abcdef\\AppData\\Local\\Temp\\\\"; // native format fs::path p3 = U"D:/猫.txt"; // UTF-32 string fs::path p4 = u8"~/狗.txt"; // UTF-8 string std::cout << "p1 = " << p1 << '\n' << "p2 = " << p2 << '\n' << "p3 = " << p3 << '\n' << "p4 = " << p4 << '\n'; } ``` -------------------------------- ### C++ Example: Constructing std::deque using deduction guides Source: https://devdocs.io/cpp/container/deque/deduction_guides An example demonstrating how to construct a std::deque using its deduction guides. It shows constructing from a std::vector's iterator range and highlights how list initialization might affect deduction. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::deque std::deque x(v.begin(), v.end()); // deduces std::deque::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::deque y{v.begin(), v.end()}; } ``` -------------------------------- ### C++ std::match_results::position Example Source: https://devdocs.io/cpp/regex/match_results/position Demonstrates how to use the std::match_results::position function to get the starting index of a captured group in a regular expression match. This function is part of the C++ standard library's regex facilities. ```cpp #include #include #include int main() { std::regex re("a(a)*b"); std::string target("aaab"); std::smatch sm; std::regex_match(target, sm, re); std::cout << sm.position(1) << '\n'; } ``` -------------------------------- ### std::print Example with File and Console Output Source: https://devdocs.io/cpp/io/print Demonstrates the usage of std::print for both console output (overload 2) and file output (overload 1). It shows how to format strings and other data types, including a std::filesystem::path. The example requires including , , and headers. ```cpp #include #include #include int main() { std::print("{0} {2}{1}!\n", "Hello", 23, "C++"); // overload (2) const auto tmp {std::filesystem::temp_directory_path() / "test.txt"}; if (std::FILE* stream{std::fopen(tmp.c_str(), "w")}) { std::print(stream, "File: {}", tmp.string()); // overload (1) std::fclose(stream); } } ``` -------------------------------- ### C++ User-defined Deduction Guide Example Source: https://devdocs.io/cpp/language/class_template_argument_deduction Demonstrates the declaration and usage of a user-defined deduction guide for a class template. It shows how the guide helps in deducing template arguments for the `container` class, including cases with implicit guides and potential errors. ```cpp // declaration of the template template struct container { container(T t) {} template container(Iter beg, Iter end); }; // additional deduction guide template container(Iter b, Iter e) -> container::value_type>; // uses container c(7); // OK: deduces T=int using an implicitly-generated guide std::vector v = {/* ... */}; auto d = container(v.begin(), v.end()); // OK: deduces T=double container e{5, 6}; // Error: there is no std::iterator_traits::value_type ``` -------------------------------- ### Create Directories Example in C++ Source: https://devdocs.io/cpp/filesystem/create_directory This C++ code example demonstrates how to use std::filesystem functions to create directories, manage permissions, copy content, and clean up using 'create_directories', 'create_directory', 'permissions', 'copy', and 'remove_all'. It utilizes the header and operates within a temporary directory. ```cpp #include #include #include #include namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/1/2/a"); fs::create_directory("sandbox/1/2/b"); fs::permissions("sandbox/1/2/b", fs::perms::others_all, fs::perm_options::remove); fs::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); std::system("tree sandbox"); fs::remove_all("sandbox"); } ``` -------------------------------- ### C++ UniquePtr Deduction Guide Example Source: https://devdocs.io/cpp/language/class_template_argument_deduction Demonstrates the use of deduction guides with the `UniquePtr` class template. It shows how `UniquePtr` can be initialized with a raw pointer and how the compiler deduces the template argument `T` using implicit deduction guides. ```cpp template struct UniquePtr { UniquePtr(T* t); }; UniquePtr dp{new auto(2.0)}; // One declared constructor: // C1: UniquePtr(T*); // Set of implicitly-generated deduction guides: // F1: template // UniquePtr F(T* p); // F2: template // UniquePtr F(UniquePtr); // copy deduction candidate // imaginary class to initialize: // struct X // { // template // X(T* p); // from F1 // // template // X(UniquePtr); // from F2 // }; // direct-initialization of an X object // with "new double(2.0)" as the initializer // selects the constructor that corresponds to the guide F1 with T = double // For F1 with T=double, the return type is UniquePtr // result: // UniquePtr dp{new auto(2.0)} ``` -------------------------------- ### C++ std::priority_queue Example Usage Source: https://devdocs.io/cpp/container/priority_queue/deduction_guides This example demonstrates how to use the deduction guides for `std::priority_queue` in C++. It shows how to construct a priority queue using a custom comparator and an initializer list, and another using an iterator range, showcasing automatic template argument deduction. ```cpp #include #include #include #include int main() { const std::vector v = {1, 2, 3, 4}; std::priority_queue pq1{std::greater{}, v}; // deduces std::priority_queue< // int, std::vector, // std::greater> for (; !pq1.empty(); pq1.pop()) std::cout << pq1.top() << ' '; std::cout << '\n'; std::priority_queue pq2{v.begin(), v.end()}; // deduces std::priority_queue for (; !pq2.empty(); pq2.pop()) std::cout << pq2.top() << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ Example: Using std::partition_copy Source: https://devdocs.io/cpp/algorithm/partition_copy This C++ example demonstrates how to use the `std::partition_copy` algorithm. It partitions an integer array into two separate arrays, one for elements greater than 4 and another for elements less than or equal to 4, printing the results. It utilizes ``, ``, and `` headers. ```cpp #include #include #include void print(auto rem, auto const& v) { for (std::cout << rem; auto const& x : v) std::cout << x << ' '; std::cout << '\n'; } int main() { int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int true_arr[5] = {0}; int false_arr[5] = {0}; std::partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr), std::begin(false_arr), [](int i) { return 4 < i; }); print("true_arr: ", true_arr); print("false_arr: ", false_arr); } ``` -------------------------------- ### C++ `std::unordered_multiset` Deduction Guides Example Source: https://devdocs.io/cpp/container/unordered_multiset/deduction_guides Demonstrates the deduction guides for `std::unordered_multiset` in C++. It shows how to construct an `unordered_multiset` using initializer lists and iterator ranges, inferring the type correctly. ```cpp #include int main() { // guide #2 deduces std::unordered_multiset std::unordered_multiset s = {1, 2, 3, 4}; // guide #1 deduces std::unordered_multiset std::unordered_multiset s2(s.begin(), s.end()); } ``` -------------------------------- ### std::vector Example Source: https://devdocs.io/cpp/container/vector A practical example demonstrating the creation, modification, and iteration of a std::vector. ```APIDOC ## Example ```cpp #include #include int main() { // Create a vector containing integers std::vector v = {8, 4, 5, 9}; // Add two more integers to vector v.push_back(6); v.push_back(9); // Overwrite element at position 2 v[2] = -1; // Print out the vector for (int n : v) std::cout << n << ' '; std::cout << '\n'; } ``` ### Output ``` 8 4 -1 9 6 9 ``` ``` -------------------------------- ### C++ Constructor Member Initializer List Example Source: https://devdocs.io/cpp/language/constructor Demonstrates how to use a member initializer list in a C++ constructor to initialize data members, reference members, and handle potential complexities with parameter shadowing. ```cpp class X { int a, b, i, j; public: const int& r; X(int i) : r(a) // initializes X::r to refer to X::a , b{i} // initializes X::b to the value of the parameter i , i(i) // initializes X::i to the value of the parameter i , j(this->i) // initializes X::j to the value of X::i {} }; ``` -------------------------------- ### C++ Unordered Map Deduction Guide Example Source: https://devdocs.io/cpp/container/unordered_map/deduction_guides Demonstrates the usage of deduction guides for `std::unordered_map` in C++. It shows how to initialize an unordered_map from an iterator range and an initializer list of pairs, highlighting the C++23 deduction guide #2 for `std::initializer_list` and guide #1 for iterator ranges. It also includes a commented-out line illustrating a compilation error. ```cpp #include #include int main() { // std::unordered_map m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type cannot // deduce pair from {"foo", 1} or {"bar", 2} // Deduction guide #2 for std::initializer_list std::unordered_map m1 = {std::pair{"foo", 2}, {"bar", 3}}; // Deduction guide #1 for iterator range std::unordered_map m2(m1.begin(), m1.end()); } ``` -------------------------------- ### C++ Deduction Guides with Member Alias Templates Source: https://devdocs.io/cpp/language/class_template_argument_deduction Shows how member alias templates in a constructor's parameter list do not affect the deducibility of the implicitly generated deduction guide. The example clarifies that the guide deduces based on the primary template's type parameter. ```cpp template struct B { template using TA = T; template B(U, TA); // #1 }; // Implicit deduction guide generated from #1 is the equivalent of // template // B(U, T) -> B; // rather than // template // B(U, typename B::template TA) -> B; // which would not have been deducible B b{(int*)0, (char*)0}; // OK, deduces B ``` -------------------------------- ### Demonstrate Sparse File Creation with resize_file Source: https://devdocs.io/cpp/filesystem/resize_file This C++ example demonstrates the effect of creating a sparse file using `std::filesystem::resize_file`. It shows how resizing a file does not immediately consume disk space on systems supporting sparse files. The code includes necessary headers and outputs file size and free space before and after resizing. ```cpp #include #include #include #include int main() { auto p = std::filesystem::temp_directory_path() / "example.bin"; std::ofstream{p}.put('a'); std::cout.imbue(std::locale{"en_US.UTF8"}); std::cout << "File size: " << std::filesystem::file_size(p) << '\n' << "Free space: " << std::filesystem::space(p).free << '\n'; std::filesystem::resize_file(p, 64*1024); // resize to 64 KB std::cout << "File size: " << std::filesystem::file_size(p) << '\n' << "Free space: " << std::filesystem::space(p).free << '\n'; std::filesystem::remove(p); } ``` -------------------------------- ### C++ Template Instantiation Examples Source: https://devdocs.io/cpp/language/partial_specialization Demonstrates how a C++ compiler resolves template instantiations using partial ordering rules. It shows cases where the primary template is used, specific partial specializations are selected, and when ambiguities lead to compilation errors. ```cpp // given the template A as defined above A a1; // no specializations match, uses primary template A a2; // uses partial specialization #1 (T = int, I = 1) A a3; // uses partial specialization #3, (T = char) A a4; // uses partial specialization #4, (X = int, T = char, I = 1) A a5; // error: matches #2 (T = int, T2 = int*, I= 2) // matches #4 (X = int*, T = int, I = 2) // neither one is more specialized than the other ``` -------------------------------- ### C++ Example: Using std::queue::swap Source: https://devdocs.io/cpp/container/queue/swap This example demonstrates the usage of `std::queue::swap`. It initializes two queues with different elements, prints their initial states, swaps their contents, and then prints their states again to show the effect of the swap operation. ```cpp #include #include #include #include #include #include template requires (std::ranges::input_range) void print(std::string_view name, const Adaptor& adaptor) { struct Printer : Adaptor // to use protected Adaptor::Container c; { void print(std::string_view name) { std::cout << name << " [" << std::size(this->c) << "]: "; for (auto const& elem : this->c) std::cout << elem << ' '; std::cout << '\n'; } }; static_cast(adaptor).print(name); } int main() { std::vector v1{"1","2","3","4"}, v2{"Ɐ","B","Ɔ","D","Ǝ"}; std::queue s1(std::move(v1)); std::queue s2(std::move(v2)); print("s1", s1); print("s2", s2); s1.swap(s2); print("s1", s1); print("s2", s2); } ``` -------------------------------- ### std::ranges::filter_view Deduction Guide Example Source: https://devdocs.io/cpp/ranges/filter_view This C++20 deduction guide for `filter_view` simplifies template argument deduction when constructing a `filter_view` from a range and a predicate. ```cpp template< class R, class Pred > filter_view( R&&, Pred ) -> filter_view, Pred>; ``` -------------------------------- ### C++: Construct unordered_multimap from iterator range and initializer list Source: https://devdocs.io/cpp/container/unordered_multimap/deduction_guides Demonstrates the deduction guides for constructing `std::unordered_multimap`. This example shows initialization from an iterator range and a correctly formed initializer list. ```cpp #include int main() { // std::unordered_multimap m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type cannot // deduce pair from {"foo", 1} or {"bar", 2} std::unordered_multimap m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::unordered_multimap m2(m1.begin(), m1.end()); // guide #1 } ``` -------------------------------- ### C++ Zero-initialization Syntax Examples Source: https://devdocs.io/cpp/language/zero_initialization Demonstrates various C++ syntax examples that can result in zero-initialization. This includes static variable declarations, default initialization of types with no constructors, and array initialization with short string literals. ```cpp static int obj; int func() { int t = {}; int another_obj {}; return 0; } char arr[5] = "abc"; ``` -------------------------------- ### Example of std::ranges::subrange usage in C++ Source: https://devdocs.io/cpp/ranges/subrange/tuple_size Demonstrates how to create and iterate over a std::ranges::subrange, and how to use std::tuple_size_v to get its size. This example requires C++20 for ranges support. ```cpp #include #include #include #include int main() { static_assert(2 == std::tuple_size_v>); using array5 = std::array; static_assert(2 == std::tuple_size>{}); constexpr array5 a{1, 2, 3, 4, 5}; std::ranges::subrange sub_a1{a}; for (std::cout << "sub_a1: { "; int e : sub_a1) std::cout << e << ' '; std::cout << "}\n"; std::ranges::subrange sub_a2{std::next(cbegin(a)), std::prev(cend(a))}; const auto [first, last] = sub_a2; std::cout << "sub_a2 size = " << std::distance(first, last) << '\n'; for (std::cout << "sub_a2: { "; int e : sub_a2) std::cout << e << ' '; std::cout << "}\n"; } ``` -------------------------------- ### C++20 Likely/Unlikely Attribute Syntax and Example Source: https://devdocs.io/cpp/language/attributes/likely Demonstrates the syntax for using the [[likely]] and [[unlikely]] attributes in C++20. These attributes can be applied to statements (excluding declaration-statements) to guide compiler optimizations. The example shows their application within a switch statement. ```cpp int f(int i) { switch (i) { case 1: [[fallthrough]]; [[likely]] case 2: return 1; } return 2; } ``` -------------------------------- ### C++ Filesystem Example: Directory Iteration and Path Extraction Source: https://devdocs.io/cpp/filesystem/directory_entry/path This C++17 example demonstrates how to iterate through a directory, create files, and extract their stems using both explicit and implicit conversions of std::filesystem::directory_entry to std::filesystem::path. It requires the , , and headers. ```cpp #include #include #include namespace fs = std::filesystem; std::string get_stem(const fs::path& p) { return p.stem().string(); } void create_file(const fs::path& p) { std::ofstream o{p}; } int main() { const fs::path dir{"tmp_dir"}; fs::create_directory(dir); create_file(dir / "one"); create_file(dir / "two"); create_file(dir / "three"); for (const auto& file : fs::directory_iterator(dir)) { // Explicit conversion std::cout << get_stem(file.path()) << '\n'; // Implicit conversion std::cout << get_stem(file) << '\n'; } fs::remove_all(dir); } ``` -------------------------------- ### C++ std::string Constructors Examples Source: https://devdocs.io/cpp/string/basic_string/basic_string Demonstrates the usage of various std::string constructors, showcasing their behavior with different input types and arguments. Includes examples for default construction, construction from character counts, substrings, C-style strings with and without explicit counts, iterators, copy construction, move construction, initializer lists, and range-based constructors. ```cpp #include #include #include #include #include #include int main() { std::cout << "1) string(); "; std::string s1; assert(s1.empty() && (s1.length() == 0) && (s1.size() == 0)); std::cout << "s1.capacity(): " << s1.capacity() << '\n'; // unspecified std::cout << "2) string(size_type count, CharT ch): "; std::string s2(4, '='); std::cout << std::quoted(s2) << '\n'; // "====" std::cout << "3) string(const string& other, size_type pos, size_type count): "; std::string const other3("Exemplary"); std::string s3(other3, 0, other3.length() - 1); std::cout << std::quoted(s3) << '\n'; // "Exemplar" std::cout << "4) string(const string& other, size_type pos): "; std::string const other4("Mutatis Mutandis"); std::string s4(other4, 8); std::cout << std::quoted(s4) << '\n'; // "Mutandis", i.e. [8, 16) std::cout << "5) string(CharT const* s, size_type count): "; std::string s5("C-style string", 7); std::cout << std::quoted(s5) << '\n'; // "C-style", i.e. [0, 7) std::cout << "6) string(CharT const* s): "; std::string s6("C-style\0string"); std::cout << std::quoted(s6) << '\n'; // "C-style" std::cout << "7) string(InputIt first, InputIt last): "; char mutable_c_str[] = "another C-style string"; std::string s7(std::begin(mutable_c_str) + 8, std::end(mutable_c_str) - 1); std::cout << std::quoted(s7) << '\n'; // "C-style string" std::cout << "8) string(string&): "; std::string const other8("Exemplar"); std::string s8(other8); std::cout << std::quoted(s8) << '\n'; // "Exemplar" std::cout << "9) string(string&&): "; std::string s9(std::string("C++ by ") + std::string("example")); std::cout << std::quoted(s9) << '\n'; // "C++ by example" std::cout << "a) string(std::initializer_list): "; std::string sa({'C', '-', 's', 't', 'y', 'l', 'e'}); std::cout << std::quoted(sa) << '\n'; // "C-style" // before C++11, overload resolution selects string(InputIt first, InputIt last) // [with InputIt = int] which behaves *as if* string(size_type count, CharT ch) // after C++11 the InputIt constructor is disabled for integral types and calls: std::cout << "b) string(size_type count, CharT ch) is called: "; std::string sb(3, std::toupper('a')); std::cout << std::quoted(sb) << '\n'; // "AAA" // std::string sc(nullptr); // Before C++23: throws std::logic_error // Since C++23: won't compile, see overload (12) // std::string sc(0); // Same as above, as literal 0 is a null pointer constant auto const range = {0x43, 43, 43}; #ifdef __cpp_lib_containers_ranges std::string sc(std::from_range, range); // tagged constructor (13) std::cout << "c) string(std::from_range, range) is called: "; #else std::string sc(range.begin(), range.end()); // fallback to overload (7) std::cout << "c) string(range.begin(), range.end()) is called: "; #endif std::cout << std::quoted(sc) << '\n'; // "C++" } ``` -------------------------------- ### Example: Reading and Setting File Write Time Source: https://devdocs.io/cpp/filesystem/last_write_time Demonstrates how to create a temporary file, get its last write time, modify it by adding an hour, and then read the updated time. This example utilizes C++17 filesystem and chrono features. ```cpp #include #include #include #include #include using namespace std::chrono_literals; int main() { auto p = std::filesystem::temp_directory_path() / "example.bin"; std::ofstream{p.c_str()}.put('a'); // create file std::filesystem::file_time_type ftime = std::filesystem::last_write_time(p); std::cout << std::format("File write time is {} ", ftime); // move file write time 1 hour to the future std::filesystem::last_write_time(p, ftime + 1h); // read back from the filesystem ftime = std::filesystem::last_write_time(p); std::cout << std::format("File write time is {} ", ftime); std::filesystem::remove(p); } ``` -------------------------------- ### Install and Trigger Signal Handler in C++ Source: https://devdocs.io/cpp/utility/program/signal This example demonstrates how to install a signal handler for SIGINT using std::signal and then trigger it using std::raise. It shows the value of a volatile sig_atomic_t variable before and after the signal is raised and processed. ```cpp #include #include namespace { volatile std::sig_atomic_t gSignalStatus; } void signal_handler(int signal) { gSignalStatus = signal; } int main() { // Install a signal handler std::signal(SIGINT, signal_handler); std::cout << "SignalValue: " << gSignalStatus << '\n'; std::cout << "Sending signal: " << SIGINT << '\n'; std::raise(SIGINT); std::cout << "SignalValue: " << gSignalStatus << '\n'; } ``` -------------------------------- ### Basic Text Formatting Example Source: https://devdocs.io/cpp/utility/format A simple C++ code example demonstrating the basic usage of `std::format` for creating formatted strings. ```APIDOC ## Basic Text Formatting Example This example shows how to use `std::format` to create a formatted string. ### Method GET ### Endpoint / ### Request Body ```cpp #include #include int main() { std::string message = std::format("The answer is {}.", 42); assert(message == "The answer is 42."); } ``` ### Response #### Success Response (200) - **message** (string) - The formatted string. #### Response Example ```json { "message": "The answer is 42." } ``` ```