Since the minimum supported GCC version was bumped to 4.6, the last barrier
for us to use "range-based for loop" from the compiler side has been
removed [1]. Now I want to remove the barrier in our lib side.

I just landed bug 1126552 [2], bug 1127044 [3], and bug 1126701 [4] in
mozilla-inbound. These three bugs together introduce some basic support for
using "range-based for loops".



Bug 1126552 introduces the range-based support for nsTArray, so if there is
an array like |nsTArray<nsIFrame*> frames|, you can now use

for (nsIFrame* frame : frames) { }

If the element type is not something small like a pointer, you probably
want to use reference or constant reference instead of the plain type to
avoid an extra copy. Also, it is generally not a good idea to use |auto| in
this case, because doing so usually reduces the readability.


Bug 1127044 makes reversely iterating possible. If you want to go through
the same array above in the different direction, you can just write

for (nsIFrame* frame : Reversed(frames)) { }



Sometimes, we still have to use the index instead of the element. That's
the reason bug 1126701 is there. First you need to #include
"mozilla/IntegerRange.h", then just

for (auto i : MakeRange(frames.Length())) { }

This statement should have the same behavior as

for (nsTArray<nsIFrame*>::size_type i = 0, iend = frames.Length(); i !=
iend; ++i) { }

but now you can benefit from the deduction of the size type, and in
addition, you don't need to use another variable for storing the length.

If you want to go from 1 to the length, you can write

for (auto i : MakeRange(1u, frames.Length())) { }

Please note the suffix "u" after the number, which is important. If you
forgot this suffix, there will be a static assertion in compile time. Also,
please make sure that the second number is not less than the first one, or
there might be an assertion in runtime.



Of course, you can combine Reversed with MakeRange to iterate the index
reversely:

for (auto i : Reversed(MakeRange(frames.Length()))) { }

This finally solves the problem I met previously [5].



With these things, let's start using range-based loop in new code. If you
have any problem using this, please complain to me. All suggestions are
welcome!

Iterating integer in arbitrary step length has not been supported. Sorry,
seth. I don't have a clear idea what's the best way to implement this yet.

[1] https://developer.mozilla.org/en-US/docs/Using_CXX_in_Mozilla_code
[2] https://bugzilla.mozilla.org/show_bug.cgi?id=1126552
[3] https://bugzilla.mozilla.org/show_bug.cgi?id=1127044
[4] https://bugzilla.mozilla.org/show_bug.cgi?id=1126701
[5]
https://groups.google.com/d/msg/mozilla.dev.platform/StyQcoAmxE8/mro6WXEZT4sJ

- Xidorn
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to