Quick Q: How to make my custom type to work with “range-based for loops”?

Quick A: Create member functions begin() and end() returning an iterator.

Recently on SO:

How to make my custom type to work with “range-based for loops”?

The standard has been changed since the question (and most answers) were posted in the resolution of this defect report.

The way to make a for(:) loop work on your type X is now one of two ways:

  • Create member X::begin() and X::end() that return something that acts like an iterator
  • Create a free function begin(X&) and end(X&) that return something that acts like an iterator, in the same namespace as your type X.

And similar for const variations. This will work both on compilers that implement the defect report changes, and compilers that do not.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.