Home >Backend Development >C++ >How Can I Make My Custom Types Work with Range-Based for Loops in C ?

How Can I Make My Custom Types Work with Range-Based for Loops in C ?

DDD
DDDOriginal
2024-12-19 22:33:16809browse

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:

  • Provide begin() and end() Member Functions:
    Implement member functions begin() and end() within your custom type that return iterators.
  • Create Free begin() and end() Functions:
    Define free functions named begin() and end() in the same namespace as your custom type, taking your type as an argument and returning iterators.

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:

  • Support pre-increment ( )
  • Provide valid initialization expressions
  • Implement binary not equal (!=) for boolean comparison
  • Expose a public destructor

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn