### C++ User-defined Deduction Guide Example Source: https://cppreference.com/w/cpp/language/ctad Demonstrates the declaration of a class template with constructors and a user-defined deduction guide to enable argument deduction. It also shows examples of using the class with different initialization methods and highlights potential errors. ```cpp 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 ``` -------------------------------- ### std::array Deduction Guide Example (C++) Source: https://cppreference.com/w/cpp/container/array/deduction_guides Demonstrates the usage of `std::array` deduction guides for constructing `std::array` objects from variadic parameter packs. It includes an example of correct usage and commented-out examples of incorrect usage, highlighting type and size constraints. The example also shows the use of `std::to_array` from C++20. ```cpp #include #include #include #include int main() { const int x = 10; std::array a{1, 2, 3, 5, x}; // OK, creates std::array assert(a.back() == x); // std::array b{1, 2u}; // Error, all arguments must have the same type // std::array c{3, 2, 1}; // Error, wrong number of template args std::array c{std::to_array({3, 2, 1})}; // C++20 facility assert(std::ranges::equal(c, std::array{3, 2, 1})); static_assert(std::is_same_v); } ``` -------------------------------- ### std::list Deduction Guides Example in C++ Source: https://cppreference.com/w/cpp/container/list/deduction_guides This C++ code snippet demonstrates the use of deduction guides for initializing a `std::list` using iterators from a `std::vector`. It highlights the difference between explicit deduction guides and list initialization. ```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()}; } ``` -------------------------------- ### Install and Use Signal Handler in C++ Source: https://cppreference.com/w/cpp/utility/program/signal This C++ code demonstrates how to install a signal handler using `std::signal`. It defines a handler function `signal_handler` that captures the signal number and installs it for `SIGINT`. The example then sends `SIGINT` using `std::raise` and prints the signal status before and after. ```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'; } ``` -------------------------------- ### Deduce iota_view with Initial and Bounding Values (C++) Source: https://cppreference.com/w/cpp/ranges/iota_view/deduction_guides This snippet demonstrates how to use the deduction guide for `std::ranges::iota_view` to initialize a view with a starting value and an ending bound. The guide helps deduce the underlying types for the initial and bounding values, ensuring type compatibility. ```cpp #include #include int main() { auto io = std::ranges::iota_view(1L, 7L); // deduces W and Bound as “long” assert(io.front() == 1L && io.back() == 6L); } ``` -------------------------------- ### C++ std::forward_list Deduction Guides Example Source: https://cppreference.com/w/cpp/container/forward_list/deduction_guides This C++ code snippet illustrates the usage of deduction guides for std::forward_list. It shows how to explicitly deduce the type using a constructor and how list-initialization behaves, potentially leading to different type deductions. ```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()}; } ``` -------------------------------- ### std::multimap Example Source: https://cppreference.com/w/cpp/container/multimap Placeholder for example usage of std::multimap, as the original content indicates no example is available. ```APIDOC ## std::multimap Example ### Description This section is intended to provide example usage of `std::multimap`. However, no example was provided in the source material. ``` -------------------------------- ### std::gslice Constructor Example Source: https://cppreference.com/w/cpp/numeric/valarray/gslice Illustrates the construction of a std::gslice object. This example demonstrates how to define a slice with a starting index, a list of strides, and a list of sizes to select a specific subset of indices from a valarray. ```cpp #include #include int main() { // Example: slice with starting index 3, strides {19, 4, 1}, and lengths {2, 4, 3} std::gslice gs(3, std::valarray({2, 4, 3}), std::valarray({19, 4, 1})); // You can then use this gslice to access elements of a valarray. // For demonstration, we'll just show the construction. std::cout << "gslice constructed successfully." << std::endl; return 0; } ``` -------------------------------- ### Create Directories Example in C++ Source: https://cppreference.com/w/cpp/filesystem/create_directory Demonstrates the basic usage of `create_directory` and `create_directories` from the `` library. It shows how to create nested directories, handle cases where a directory already exists, and manage file permissions. The example concludes by cleaning up the created directories. ```cpp #include #include #include int main() { std::filesystem::current_path(std::filesystem::temp_directory_path()); // Basic usage std::filesystem::create_directories("sandbox/1/2/a"); std::filesystem::create_directory("sandbox/1/2/b"); // Directory already exists (false returned, no error) assert(!std::filesystem::create_directory("sandbox/1/2/b")); // Permissions copying usage std::filesystem::permissions( "sandbox/1/2/b", std::filesystem::perms::others_all, std::filesystem::perm_options::remove ); std::filesystem::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); std::system("tree sandbox"); std::filesystem::remove_all("sandbox"); } ``` -------------------------------- ### Get std::function target type with C++ example Source: https://cppreference.com/w/cpp/utility/functional/function/target_type This example demonstrates how to use std::function::target_type to retrieve the type information of stored function objects. It shows that different function objects, even with the same signature, will have distinct type information, and also illustrates C++17's deduction guides. ```cpp #include #include int f(int a) { return -a; } void g(double) {} int main() { // fn1 and fn2 have the same type, but their targets do not std::function fn1(f), fn2([](int a) {return -a;}); std::cout << fn1.target_type().name() << '\n' << fn2.target_type().name() << '\n'; // since C++17 deduction guides (CTAD) can avail std::cout << std::function{g}.target_type().name() << '\n'; } ``` -------------------------------- ### Aggregate Initialization Examples (C++) Source: https://cppreference.com/w/cpp/language/aggregate_initialization Demonstrates aggregate initialization using various scenarios, including designated initializers for unions and classes. It highlights valid and invalid initializations based on C++ rules. ```cpp union u { int a; const char* b; }; u a = {1}; // OK: explicitly initializes member `a` u b = {0, "asdf"}; // error: explicitly initializes two members u c = {"asdf"}; // error: int cannot be initialized by "asdf" // C++20 designated initializer lists u d = {.b = "asdf"}; // OK: can explicitly initialize a non-initial member u e = {.a = 1, .b = "asdf"}; // error: explicitly initializes two members ``` ```cpp struct C { union { int a; const char* p; }; int x; } c = {.a = 1, .x = 3}; // initializes c.a with 1 and c.x with 3 ``` ```cpp struct A { int x; struct B { int i; int j; } b; } a = {1, {2, 3}}; // initializes a.x with 1, a.b.i with 2, a.b.j with 3 struct base1 { int b1, b2 = 42; }; struct base2 { base2() { b3 = 42; } int b3; }; struct derived : base1, base2 { int d; }; derived d1{{1, 2}, {}, 4}; // initializes d1.b1 with 1, d1.b2 with 2, // d1.b3 with 42, d1.d with 4 derived d2{{}, {}, 4}; // initializes d2.b1 with 0, d2.b2 with 42, // d2.b3 with 42, d2.d with 4 ``` ```cpp struct S { int a; const char* b; int c; int d = b[a]; }; // initializes ss.a with 1, // ss.b with "asdf", // ss.c with the value of an expression of the form int{} (that is, 0), // and ss.d with the value of ss.b[ss.a] (that is, 's') S ss = {1, "asdf"}; ``` -------------------------------- ### C++ Variable Initialization Examples Source: https://cppreference.com/w/cpp/language/initialization Demonstrates various C++ initialization syntaxes including default, copy, direct, and list initialization for std::string objects, as well as aggregate initialization for a char array. ```cpp #include std::string s1; std::string s2(); std::string s3 = "hello"; std::string s4("hello"); std::string s5{'a'}; char a[3] = {'a', 'b'}; char& c = a[0]; ``` -------------------------------- ### C++ UniquePtr Deduction Guide Example Source: https://cppreference.com/w/cpp/language/ctad Demonstrates class template argument deduction for `UniquePtr` using fictional constructors and deduction guides. The example shows how the initializer `new auto(2.0)` leads to the deduction of `T = double` and the selection of the appropriate deduction guide. ```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)} ``` -------------------------------- ### Generate qch Book with Bash Source: https://cppreference.com/w/cpp/w/Cppreference_talk%253AArchives This bash script demonstrates how to rebuild a qch (Qt Help Collection) book from a directory of files. It involves copying an XML file, using the `qhelpgenerator` command to create the `.qch` file, and then cleaning up temporary files. This is useful for updating offline documentation. ```bash cp qch-help-project.xml output/qch.xml pushd "output"; qhelpgenerator qch.xml -o "../cppreference-doc-en.qch"; popd rm -f output/qch.xml ``` -------------------------------- ### C++ S::N Deduction Guide Example Source: https://cppreference.com/w/cpp/language/ctad Illustrates class template argument deduction for a nested template `S::N`. The example details the implicitly-generated deduction guides and explains how overload resolution selects the correct guide (F3 in this case) for the given initializer ` {2.0, 1}`. ```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}; ``` -------------------------------- ### Create and Verify Hard Link (C++) Source: https://cppreference.com/w/cpp/experimental/fs/create_hard_link Demonstrates creating directories, a regular file, and then a hard link to that file using `std::experimental::filesystem`. It verifies the hard link by reading from it after the original file is removed. Finally, it cleans up the created sandbox directory. This requires the `` header. ```cpp #include #include #include namespace fs = std::experimental::filesystem; int main() { fs::create_directories("sandbox/subdir"); std::ofstream("sandbox/a").put('a'); // create regular file fs::create_hard_link("sandbox/a", "sandbox/b"); fs::remove("sandbox/a"); // read from the original file via surviving hard link char c = std::ifstream("sandbox/b").get(); std::cout << c << '\n'; fs::remove_all("sandbox"); } ``` -------------------------------- ### User-defined deduction guide syntax and example Source: https://cppreference.com/w/cpp/language/deduction_guide Demonstrates the syntax of a user-defined deduction guide for a C++ class template. It shows how to declare a deduction guide that allows the compiler to deduce template arguments based on constructor parameters, including an example of its usage and a compilation error scenario. ```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 ``` -------------------------------- ### Example Usage of std::basic_string_view Deduction Guides Source: https://cppreference.com/w/cpp/string/basic_string_view/deduction_guides This C++ example demonstrates how deduction guides for std::basic_string_view automatically deduce the character type from different array types using iterator-sentinel pairs. It showcases deduction for `char`, `wchar_t`, and a custom type `long`. ```cpp #include #include #include   int main() { std::array a1{'n', 'u', 'c', 'l', 'e', 'o', 'n', 's', ':', '\n'}; std::basic_string_view s1(a1.cbegin(), a1.cend()); // deduction: CharT -> char static_assert(std::is_same_v); std::cout << s1;   std::array a2{L'p', L'r', L'o', L't', L'o', L'n', L's', L'\n'}; std::basic_string_view s2(a2.cbegin(), a2.cend()); // deduction: CharT -> wchar_t static_assert(std::is_same_v); std::wcout << s2;   std::array a3{'n', 'e', 'u', 't', 'r', 'o', 'n', 's', '\n'}; std::basic_string_view s3(a3.cbegin(), a3.cend()); // deduction: CharT -> long static_assert(std::is_same_v); for (const auto e : s3) std::cout << static_cast(e); } ``` -------------------------------- ### Value-initialization Syntax in C++ Source: https://cppreference.com/w/cpp/language/value_initialization Demonstrates the different ways to perform value-initialization in C++ for various types and contexts. This includes direct initialization, new expressions, and member initialization lists. ```cpp T object(); new T(); Class::Class(...): member() { ... } T object{}; T {}; new T {}; Class::Class(...): member{} { ... } ``` -------------------------------- ### Reference Template Example (Wiki Syntax) Source: https://cppreference.com/w/cpp/w/Cppreference_talk%253AFAQ An example of how reference entries for C++ standards could be formatted using wiki markup. This facilitates structured citation of different standard versions and sections. ```wiki ===References=== {{ref std c++11}} {{ref std | section=8.3.5 | title=Functions | id=dcl.fct}} {{ref std | section=8.3.6 | title=Default arguments | id=dcl.fct.default | p=1-2,4}} {{ref std c++98}} ... ``` -------------------------------- ### C++ Deduction Guides for Non-Template Structs Source: https://cppreference.com/w/cpp/language/ctad Shows how deduction guides can be used even for non-template structs. This example demonstrates deducing a std::string from a C-style string literal using a deduction guide. ```cpp template struct S { S(T); }; S(char const*) -> S;   S s{"hello"}; // deduced to S ``` -------------------------------- ### Example Usage of std::partition and Quicksort Source: https://cppreference.com/w/cpp/algorithm/partition This example demonstrates the usage of std::partition and a custom quicksort implementation that utilizes std::partition. The main function first partitions a vector of integers, separating even numbers from odd numbers. It then shows a quicksort algorithm applied to a forward_list of integers, sorting them in ascending order. The output shows the original and partitioned vectors, as well as the original and sorted forward_list. ```cpp #include #include #include #include #include template void quicksort(ForwardIt first, ForwardIt last) { if (first == last) return; auto pivot = *std::next(first, std::distance(first, last) / 2); auto middle1 = std::partition(first, last, [pivot](const auto& em) { return em < pivot; }); auto middle2 = std::partition(middle1, last, [pivot](const auto& em) { return !(pivot < em); }); quicksort(first, middle1); quicksort(middle2, last); } int main() { std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::cout << "Original vector: "; for (int elem : v) std::cout << elem << ' '; auto it = std::partition(v.begin(), v.end(), [](int i) {return i % 2 == 0;}); std::cout << "\nPartitioned vector: "; std::copy(std::begin(v), it, std::ostream_iterator(std::cout, " ")); std::cout << "* "; std::copy(it, std::end(v), std::ostream_iterator(std::cout, " ")); std::forward_list fl {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92}; std::cout << "\nUnsorted list: "; for (int n : fl) std::cout << n << ' '; quicksort(std::begin(fl), std::end(fl)); std::cout << "\nSorted using quicksort: "; for (int fi : fl) std::cout << fi << ' '; std::cout << '\n'; } ``` -------------------------------- ### std::unordered_set Construction Example Source: https://cppreference.com/w/cpp/container/unordered_set/deduction_guides This example demonstrates the usage of deduction guides for std::unordered_set in C++. It shows how to construct a set directly from an initializer list and from a range using iterators, relying on compiler deduction for template arguments. ```cpp #include #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()); // Example using std::from_range (C++23) std::vector data = {5, 6, 7}; std::unordered_set from_range_set(std::from_range, data); } ``` -------------------------------- ### C++ forward_list begin and cbegin example Source: https://cppreference.com/w/cpp/container/forward_list/begin This example demonstrates how to use std::forward_list::begin and std::forward_list::cbegin to access elements for iteration and manipulation. It shows printing elements, calculating sums, accessing the first element, and verifying an empty list. ```cpp #include #include #include #include #include int main() { std::forward_list nums{1, 2, 4, 8, 16}; std::forward_list fruits{"orange", "apple", "raspberry"}; std::forward_list empty; // Print forward_list. std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the forward_list nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; // Prints the first fruit in the forward_list fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.begin() << '\n'; if (empty.begin() == empty.end()) std::cout << "forward_list 'empty' is indeed empty.\n"; } ``` -------------------------------- ### CTAD for Aggregates with Deduction Guides - C++ Source: https://cppreference.com/w/cpp/language/deduction_guide Illustrates Class Template Argument Deduction for aggregate types using user-defined deduction guides. In C++20, some deduction guides can be implicitly generated. This example shows how a custom guide allows deduction for an aggregate struct. ```cpp template struct Agg { A a; B b; }; // implicitly-generated guides are formed from default, copy, and move constructors template Agg(A a, B b) -> Agg; // ^ This deduction guide can be implicitly generated in C++20 Agg agg{1, 2.0}; // deduced to Agg from the user-defined guide template array(T&&... t) -> array, sizeof...(T)>; auto a = array{1, 2, 5u}; // deduced to array from the user-defined guide ``` -------------------------------- ### C++ std::begin(std::initializer_list) Example Source: https://cppreference.com/w/cpp/utility/initializer_list/begin2 This C++ code snippet demonstrates the usage of std::begin and std::end with an std::initializer_list to copy its elements to standard output. It includes necessary headers like , , , and . ```cpp #include #include #include #include   int main() { std::initializer_list ϕ = {'1', '.', '6', '1', '8', '0'};   std::copy(std::begin(ϕ), std::end(ϕ), std::ostream_iterator(std::cout, ""));   std::cout << '\n'; } ``` -------------------------------- ### std::shared_ptr Deduction Guides Example (C++17) Source: https://cppreference.com/w/cpp/memory/shared_ptr/deduction_guides Demonstrates the usage of explicit deduction guides for std::shared_ptr when initializing from std::weak_ptr. These guides simplify the creation of shared_ptr objects by allowing template argument deduction. ```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 } ``` -------------------------------- ### std::optional Constructors and Initialization Example Source: https://cppreference.com/w/cpp/utility/optional/optional Illustrates various ways to construct and initialize std::optional objects. This includes default construction, initialization from values, copy construction, and using std::in_place with different string constructors. It also shows the use of deduction guides for constructing optional objects. ```cpp #include #include #include int main() { std::optional o1, // empty o2 = 1, // init from rvalue o3 = o2; // copy-constructor // calls std::string( initializer_list ) constructor std::optional o4(std::in_place, {'a', 'b', 'c'}); // calls std::string( size_type count, CharT ch ) constructor std::optional o5(std::in_place, 3, 'A'); // Move-constructed from std::string using deduction guide to pick the type std::optional o6(std::string{"deduction"}); std::cout << *o2 << ' ' << *o3 << ' ' << *o4 << ' ' << *o5 << ' ' << *o6 << '\n'; } ``` -------------------------------- ### C++23 std::map Deduction Guides Example Source: https://cppreference.com/w/cpp/container/map/deduction_guides This example demonstrates the usage of std::map deduction guides in C++23. It shows how to initialize a map from an initializer list of std::pair and from an iterator range. The commented-out line illustrates a common pitfall where direct initialization from a braced-init-list of string literals can lead to compilation errors due to type deduction issues. ```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 } ``` -------------------------------- ### Example: Formatting a set of strings Source: https://cppreference.com/w/cpp/utility/format/format Provides a practical example of using std::format to output a std::set of strings. The output demonstrates how the set is formatted by default. This example is conditional on the `__cpp_lib_format_ranges` feature test macro. ```cpp #ifdef __cpp_lib_format_ranges const std::set continents { "Africa", "America", "Antarctica", "Asia", "Australia", "Europe" }; std::cout << std::format("Hello {}!\n", continents); #else std::cout << std::format("Hello {}!\n", "continents"); #endif ``` -------------------------------- ### Demonstrate std::filesystem::relative and std::filesystem::proximate Source: https://cppreference.com/w/cpp/filesystem/relative This C++ code snippet demonstrates the usage of `std::filesystem::relative` and `std::filesystem::proximate` functions. It defines a helper function `show` to display the results of these functions for different path pairs and then calls `show` with various examples in the `main` function. The code requires the `` and `` headers. ```cpp #include #include void show(std::filesystem::path x, std::filesystem::path y) { std::cout << "x:\t\t " << x << "\ny:\t\t " << y << '\n' << "relative(x, y): " << std::filesystem::relative(x, y) << '\n' << "proximate(x, y): " << std::filesystem::proximate(x, y) << "\n\n"; } int main() { show("/a/b/c", "/a/b"); show("/a/c", "/a/b"); show("c", "/a/b"); show("/a/b", "c"); } ``` -------------------------------- ### std::pair Deduction Guide Example (C++) Source: https://cppreference.com/w/cpp/utility/pair/deduction_guides This C++ code snippet demonstrates the usage of the deduction guide for std::pair, introduced in C++17. It shows how the explicit deduction guide is used when declaring a pair with array types. ```cpp #include int main() { int a[2], b[3]; std::pair p{a, b}; // explicit deduction guide is used in this case } ``` -------------------------------- ### C++ Explicit Deduction Guides and Initialization Contexts Source: https://cppreference.com/w/cpp/language/ctad Illustrates the effect of explicit constructors and explicit user-defined deduction guides on initialization contexts, particularly copy-initialization versus direct-initialization. It shows how explicit guides are handled and their impact on overload resolution. ```cpp template struct A { explicit A(const T&, ...) noexcept; // #1 A(T&&, ...); // #2 };   int i; A a1 = {i, i}; // error: cannot deduce from rvalue reference in #2, // and #1 is explicit, and not considered in copy-initialization. A a2{i, i}; // OK, #1 deduces to A and also initializes A a3{0, i}; // OK, #2 deduces to A and also initializes A a4 = {0, i}; // OK, #2 deduces to A and also initializes   template A(const T&, const T&) -> A; // #3   template explicit A(T&&, T&&) -> A; // #4   A a5 = {0, 1}; // error: #3 deduces to A // and #1 & #2 result in same parameter constructors. A a6{0, 1}; // OK, #4 deduces to A and #2 initializes A a7 = {0, i}; // error: #3 deduces to A A a8{0, i}; // error: #3 deduces to A   // Note: check https://github.com/cplusplus/CWG/issues/647, claiming that // examples a7 and a8 are incorrect, to be possibly replaced as //A a7 = {0, i}; // error: #2 and #3 both match, overload resolution fails //A a8{i,i}; // error: #3 deduces to A, // // #1 and #2 declare same constructor ``` -------------------------------- ### C++ std::basic_regex Deduction Guide Example Source: https://cppreference.com/w/cpp/regex/basic_regex/deduction_guides This C++ code snippet demonstrates the usage of the std::basic_regex deduction guide, which infers the template type from an iterator range. It requires the `` and `` headers. The guide is available since C++17. ```cpp #include #include int main() { std::vector v = {'a', 'b', 'c'}; std::basic_regex re(v.begin(), v.end()); // uses explicit deduction guide } ``` -------------------------------- ### C++20 std::print and std::println Example Source: https://cppreference.com/w/cpp/utility/format/runtime_format Demonstrates the usage of std::print and std::println for formatted output to the console using std::runtime_format. This example requires C++20 support. It shows dynamic formatting string construction and output. ```cpp #include #include #include #include int main() { std::print("Hello {}!\n", "world"); std::string fmt; for (int i{}; i != 3; ++i) { fmt += "{} "; // constructs the formatting string std::print("{} : ", fmt); std::println(std::runtime_format(fmt), "alpha", 'Z', 3.14, "unused"); } } ``` -------------------------------- ### C++ Filesystem Path Construction Example Source: https://cppreference.com/w/cpp/experimental/fs/path/path This C++ code snippet demonstrates how to construct std::experimental::filesystem::path objects from portable format, native format, and wide string literals. It utilizes the header and outputs the constructed paths to the console. ```cpp #include #include namespace fs = std::experimental::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 = L"D:/猫.txt"; // wide string std::cout << "p1 = " << p1 << '\n' << "p2 = " << p2 << '\n' << "p3 = " << p3 << '\n'; } ``` -------------------------------- ### C++ filter_view Deduction Guide Example Source: https://cppreference.com/w/cpp/ranges/filter_view Demonstrates the usage of a deduction guide for the filter_view in C++20, which simplifies template instantiation by allowing the compiler to deduce types. This guide helps in creating filter_view objects without explicitly specifying template arguments. ```cpp template< class R, class Pred > filter_view( R&&, Pred ) -> filter_view, Pred>; (since C++20) ``` -------------------------------- ### C++ Example: Initializer List Construction for unordered_map Source: https://cppreference.com/w/cpp/container/unordered_map/deduction_guides Demonstrates how to correctly initialize an std::unordered_map using an initializer list in C++. It highlights the necessary use of std::pair to resolve ambiguity in deduction for Key and T types, as shown in the commented-out error example and the corrected guide #2 usage. ```cpp #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} std::unordered_map m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::unordered_map m2(m1.begin(), m1.end()); // guide #1 } ``` -------------------------------- ### Demonstrate std::filesystem::permissions with perm_options C++ Source: https://cppreference.com/w/cpp/filesystem/perm_options This C++ code example demonstrates how to use std::filesystem::permissions in conjunction with std::filesystem::perm_options. It shows how to create a file, display its initial permissions, add specific permissions using 'add' option, and then display the updated permissions. The 'demo_perms' function helps visualize the permission bits. ```cpp #include #include #include void demo_perms(std::filesystem::perms p) { using std::filesystem::perms; auto show = [=](char op, perms perm) { std::cout << (perms::none == (perm & p) ? '-' : op); }; show('r', perms::owner_read); show('w', perms::owner_write); show('x', perms::owner_exec); show('r', perms::group_read); show('w', perms::group_write); show('x', perms::group_exec); show('r', perms::others_read); show('w', perms::others_write); show('x', perms::others_exec); std::cout << '\n'; } int main() { std::ofstream("test.txt"); // create file std::cout << "Created file with permissions: "; demo_perms(std::filesystem::status("test.txt").permissions()); std::filesystem::permissions( "test.txt", std::filesystem::perms::owner_all | std::filesystem::perms::group_all, std::filesystem::perm_options::add ); std::cout << "After adding u+rwx and g+rwx: "; demo_perms(std::filesystem::status("test.txt").permissions()); std::filesystem::remove("test.txt"); } ``` -------------------------------- ### C++ ifstream Constructors Example Source: https://cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream Demonstrates the different ways to construct a std::ifstream object. This includes opening files by name, using binary mode, and moving from existing ifstream objects. ```cpp #include #include #include   int main() { std::ifstream f0; std::ifstream f1("test.bin", std::ios::binary); std::string name = "example.txt"; std::ifstream f2(name); std::ifstream f3(std::move(f1)); } ``` -------------------------------- ### std::valarray Deduction Guide Example (C++) Source: https://cppreference.com/w/cpp/numeric/valarray/deduction_guides This snippet demonstrates the usage of the std::valarray deduction guide in C++17. It initializes a std::valarray from a C-style array and a size, then iterates and prints its elements. Note that the deduction guide is used explicitly here, and the output reflects the specified size. ```cpp #include #include int main() { int a[] = {1, 2, 3, 4}; std::valarray va(a, 3); // uses explicit deduction guide for (int x : va) std::cout << x << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ User-Defined Deduction Guides for Aggregates Source: https://cppreference.com/w/cpp/language/ctad Illustrates the use of user-defined deduction guides for aggregate classes. It shows how to define a guide to enable CTAD for aggregates, which typically requires explicit guides before C++20. ```cpp template struct Agg { A a; B b; }; // implicitly-generated guides are formed from default, copy, and move constructors   template Agg(A a, B b) -> Agg; // ^ This deduction guide can be implicitly generated in C++20   Agg agg{1, 2.0}; // deduced to Agg from the user-defined guide   template array(T&&... t) -> array, sizeof...(T)>; auto a = array{1, 2, 5u}; // deduced to array from the user-defined guide ``` -------------------------------- ### C++ Deque Basic Operations Example Source: https://cppreference.com/w/cpp/container/deque This C++ code snippet demonstrates the creation of a std::deque, adding elements to its front and back using push_front and push_back, and then iterating through the deque to print its contents. It requires the `` and `` headers. ```cpp #include #include   int main() { // Create a deque containing integers std::deque d = {7, 5, 16, 8};   // Add an integer to the beginning and end of the deque d.push_front(13); d.push_back(25);   // Iterate and print values of deque for (int n : d) std::cout << n << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ split_view Deduction Guides Example Source: https://cppreference.com/w/cpp/ranges/split_view/deduction_guides This C++ snippet demonstrates the usage of deduction guides for std::ranges::split_view with string views and single characters as delimiters. It uses static_assert to verify the deduced types. ```cpp #include #include #include using std::operator""sv; int main() { std::ranges::split_view w1{"a::b::c"sv, "::"sv}; static_assert(std::is_same_v< decltype(w1), std::ranges::split_view>); std::ranges::split_view w2{"x,y,z"sv, ','}; static_assert(std::is_same_v< decltype(w2), std::ranges::split_view>>); } ``` -------------------------------- ### observer_ptr Constructor Documentation Source: https://cppreference.com/w/cpp/experimental/observer_ptr/observer_ptr Documentation for the different ways to construct an std::experimental::observer_ptr. ```APIDOC ## observer_ptr::observer_ptr Constructors ### Description Provides documentation for the various constructors of the `std::experimental::observer_ptr` class, allowing for initialization with nullptr, a raw pointer, or another observer_ptr. ### Method Constructor ### Endpoint N/A (Class Member Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp // Example of constructing an observer_ptr int x = 5; std::experimental::observer_ptr ptr1(&x); // Using a raw pointer std::experimental::observer_ptr ptr2 = ptr1; // Copy constructor std::experimental::observer_ptr ptr3(nullptr); // Using nullptr ``` ### Response #### Success Response (Constructor) - **observer_ptr** (Constructor) - Constructs an `observer_ptr` object. #### Response Example ```cpp // After construction, ptr1, ptr2, and ptr3 are valid observer_ptr objects. // ptr1 and ptr2 will point to x, ptr3 will be null. ``` ``` -------------------------------- ### C++ weak_ptr Deduction Guide Example Source: https://cppreference.com/w/cpp/memory/weak_ptr/deduction_guides This C++ code snippet demonstrates the usage of std::make_shared to create a shared pointer and then initializes a std::weak_ptr from it. It highlights the role of deduction guides in managing smart pointers. ```cpp #include int main() { auto p = std::make_shared(42); std::weak_ptr w{p}; // explicit deduction guide is used in this case } ``` -------------------------------- ### std::experimental::any::any Constructors Source: https://cppreference.com/w/cpp/experimental/any/any Provides documentation for the various constructors of the std::experimental::any class. ```APIDOC ## any::any Constructors ### Description Constructs a new `any` object. This includes creating an empty object, copying or moving from another `any` object, or initializing with a specific value. ### Method Constructors ### Parameters - **other** (*any*) - Required - Another `any` object to copy or move from. - **value** (*ValueType*) - Required - The value to initialize the contained value with. ### Template Parameters - **ValueType** - The type of the value to be contained. ### Exceptions - Throws any exception thrown by the constructor of the contained type. ### See also - `operator=` - Assigns an `any` object. ### Overloads 1. `any() noexcept;` - Constructs an empty object. 2. `any( const any& other );` - Copies content of `other` into a new instance. 3. `any( any&& other ) noexcept;` - Moves content of `other` into a new instance. 4. `template any( ValueType&& value );` - Constructs an object with initial content of type `std::decay_t`. ``` -------------------------------- ### C++ std::queue Deduction Guide Example Source: https://cppreference.com/w/cpp/container/queue/deduction_guides This C++ code snippet demonstrates the use of deduction guides for `std::queue`. It initializes a `std::vector` and then constructs a `std::queue` from it, allowing the compiler to deduce the container type. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; std::queue s{v}; // guide #1 deduces std::queue> } ``` -------------------------------- ### CTAD with Non-Template Deduction Guides - C++ Source: https://cppreference.com/w/cpp/language/deduction_guide Shows how user-defined deduction guides, even if not templates themselves, can facilitate Class Template Argument Deduction. This example deduces a std::string type for a specialized struct. ```cpp template struct S { S(T); }; S(char const*) -> S; S s{"hello"}; // deduced to S ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.