C fold expressions example
Cfold expressions is a feature introduced in C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args ...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args && ...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout
Cfold expressions is a feature introduced by C 17, which is mainly used to concisely perform recursive operations on parameter packages in variadic templates. It is often used in scenarios such as summing, logical judgment, printing, etc., and combined with ...
and operators, it can greatly simplify the code.

The following is a few typical examples to illustrate the usage of fold expressions.
✅ 1.Summarize the parameter package (left fold)
#include <iostream> template<typename... Args> auto sum(Args... args) { return (args ...); // Left fold: (((ab) c) ...) } int main() { std::cout << sum(1, 2, 3, 4, 5) << std::endl; // Output 15 return 0; }
Here
(args ...)
will add all parameters from left to right.
✅ 2. Check that all boolean values are true (and judge)
template<typename... Args> bool all_true(Args... args) { return (args && ...); // Left fold, equivalent to: args1 && args2 && ... } int main() { std::cout << std::boolalpha; std::cout << all_true(true, true, false) << std::endl; // Output false std::cout << all_true(true, true, true) << std::endl; // Output true return 0; }
If the parameter package is empty,
&&
collapse will returntrue
(becausetrue
is the unit element of logical AND).
✅ 3. Print all parameters (using comma operator)
#include <iostream> template<typename... Args> void print(Args... args) { (std::cout << ... << args) << '\n'; // Right fold: args1 << (args2 << (args3 << cout)) } int main() { print("Hello", " ", "world", "!", 2024); // Output: Hello world!2024 return 0; }
Use commas
,
operators to achieve output one by one. Note that here is right fold(... << args)
or(args << ...)
, but here we use(std::cout << ... << args)
, which is the binary fold that the package expands in the middle of the operator .
✅ 4. Supports folding of default values (with initial value)
You can also provide an initial value to the folder expression:
template<typename... Args> auto sum_with_init(Args... args) { return (args ... 10); // Add 10 at the end, which is equivalent to: (((ab) c) ... 10) } int main() { std::cout << sum_with_init(1, 2, 3) << std::endl; // 1 2 3 10 = 16 return 0; }
Note:
(args ... 10)
is right folded, equivalent toargs1 (args2 (args3 10))
, but the addition satisfies the law of binding, and the result is the same.
✅ 5. Processing of empty parameter packages
template<typename... Args> bool all(Args... args) { return (args && ...); // Return true when empty parameter package } template<typename... Args> bool any(Args... args) { return (args || ...); // Return false when empty parameter package } int main() { std::cout << all() << std::endl; // true std::cout << any() << std::endl; // false return 0; }
&&
Fold empty package →true
||
Fold empty package →false
Collapse of empty packages will fail to compile (no default value)
? Summary: The syntax form of folded expressions
type | grammar | illustrate |
---|---|---|
One dollar left fold | (pack op ...)
|
For example (args ...)
|
One dollar right fold | (... op pack)
|
For example (... args)
|
Binary folding | (pack op ... op init) or (init op ... op pack)
|
With initial value |
Basically these common uses. fold expressions make variadic template programming concise and intuitive, avoiding the complex writing of recursive templates. Not complicated but it is easy to ignore details, such as empty package behavior and combination direction.
The above is the detailed content of C fold expressions example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

C folderexpressions is a feature introduced by C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args&&...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout

TodebugaC applicationusingGDBinVisualStudioCode,configurethelaunch.jsonfilecorrectly;keysettingsincludespecifyingtheexecutablepathwith"program",setting"MIMode"to"gdb"and"type"to"cppdbg",using"ex

The system endianness can be detected by a variety of methods, the most commonly used is the union or pointer method. 1. Use a union: Assign uint32_t to 0x01020304, if the lowest address byte is 0x04, it is a small endian, and if it is 0x01, it is a big endian; 2. Use pointer conversion: Assign uint16_t to 0x0102, read the byte order through the uint8_t pointer, [0]==0x02 and [1]==0x01 is a small endian, otherwise it is a big endian; 3. Compilation-time detection: define the constexpr function to determine whether the (char)&int variable is 1, and combine ifconstexpr to determine the endian order during the compilation period; 4. Runtime macro encapsulation: use (char*)&

The answer is: Use the std::string constructor to convert the char array to std::string. If the array contains the intermediate '\0', the length must be specified. 1. For C-style strings ending with '\0', use std::stringstr(charArray); to complete the conversion; 2. If the char array contains the middle '\0' but needs to convert the first N characters, use std::stringstr(charArray,length); to clearly specify the length; 3. When processing a fixed-size array, make sure it ends with '\0' and then convert it; 4. Use str.assign(charArray,charArray strl

The most common method of finding vector elements in C is to use std::find. 1. Use std::find to search with the iterator range and target value. By comparing whether the returned iterator is equal to end(), we can judge whether it is found; 2. For custom types or complex conditions, std::find_if should be used and predicate functions or lambda expressions should be passed; 3. When searching for standard types such as strings, you can directly pass the target string; 4. The complexity of each search is O(n), which is suitable for small-scale data. For frequent searches, you should consider using std::set or std::unordered_set. This method is simple, effective and widely applicable to various search scenarios.

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Using std::mutex and std::lock_guard can avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. Avoid deadlocks and multiple locks in a fixed order; 5. Any scenario of multi-thread access to shared resources should use mutex synchronization, and the final program correctly outputs Expected:10000 and Actual:10000.

Install the g compiler (Windows uses MinGW-w64, macOS runs xcode-select--install, and Linux executes sudoaptinstallbuild-essential); 2. Create a C.sublime-build file in SublimeText and fill in the specified JSON configuration; 3. After opening the .cpp file, press Ctrl B to compile, press Ctrl Shift B to select Run to compile and run, and the output results will be displayed in the bottom panel.

Install the Boost library, 2. Write code for DNS resolution using Boost.Asio, 3. Compile and link the boost_system library, 4. Run the program to output the IP address parsed by www.google.com; this example shows how Boost.Asio simplifies network programming in C, implements cross-platform, type-safe synchronous DNS queries through io_context and tcp::resolver, and supports IPv4 and IPv6 address resolution, and finally prints all resolution results.
