Microsoft "for each" patch

endlessroad1991 at gmail.com endlessroad1991 at gmail.com
Wed Apr 17 02:21:02 PDT 2013


MSVC supports for-each for 3 conditions:
    1. C-style array: int arr[10]; for each (int &i in arr) {}
    2. std::vector style iterators: vector<int> v; for each (int &i in v) {}
    3. The most complex one, the one like in C#:

#include <iostream>

#define ARRAY_SIZE 3
int arr[ARRAY_SIZE] = { 1, 3, 5 };

struct Enumerator {
  __declspec(property) int& Current;
  int& GetCurrent() { return arr[index]; }

  bool MoveNext() { index++; return index < ARRAY_SIZE; }

  Enumerator() { index = -1; }
  int index;
};

struct Collection {
  Enumerator GetEnumerator() { return Enumerator(); }
};

int main() {
  Collection c;
  // Output: 1 \n 3 \n 5 \n
  for each (int& i in c) {
    std::cout << i << "\n";
  }
}

      The class that is "foreach"ed must have a method which returns a
enumerator class.
      And this enumerator class must have a property named "Current" and a
"bool MoveNext()".

for each (T elem in collection) stmt

      is translated to:

{
  auto&& enumerator = collection.getEnumerator();
  while (enumerator.MoveNext()) {
    T elem = enumerator.Current; // Current is a property!!!
    stmt
  }
}

1. This patch only solves (3).
2. Enumerator class should have "Current" as a property, but for simplicity
I just translate to enumarator.GetCurrent(), instead of enumerator.Current
3. The logic is kind of mixed up with C++11 for-range loop. So there may be
some warnings like "for-range loop is C++11 extension", while we are using
foreach...

This patch is proved to behave correctly UNDER CORRENT CODE, and is used in
our product generation.

-- 
Best Regards, Tong Shen (沈彤)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20130417/d11098a9/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 1.patch
Type: application/octet-stream
Size: 24172 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20130417/d11098a9/attachment.obj>


More information about the cfe-commits mailing list