Home >Backend Development >C++ >How Can I Make My Custom Types Work with Range-Based for Loops in C ?
Making Custom Types Compatible with Range-Based for Loops
To enable the use of range-based for loops with custom data types, you have two primary options:
Namespace Considerations:
If your custom type resides in a namespace, such as xml, you must declare the begin() and end() functions within that namespace as well. There is no requirement to specify either xml::begin() or std::begin().
Method Requirements:
The begin/end return values are not required to be actual iterators. However, they must adhere to specific requirements:
Range-Based for Loop Expansion:
The range-based for loop syntax, for (range_declaration : range_expression), expands to the following pseudocode:
{ auto &range = range_expression; for (auto begin = begin_expr, end = end_expr; begin != end; ++begin) { range_declaration = *begin; loop_statement } }
C 17 Decoupled End Types:
In C 17, the range-based for loop expanded pseudocode changed to:
{ auto &range = range_expression; auto begin = begin_expr; auto end = end_expr; for (; begin != end; ++begin) { range_declaration = *begin; loop_statement } }
This change allows the end iterator type to differ from the begin iterator type. It enables the use of "sentinel" iterators that only support inequality comparisons with the begin iterator type.
The above is the detailed content of How Can I Make My Custom Types Work with Range-Based for Loops in C ?. For more information, please follow other related articles on the PHP Chinese website!