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 (沈彤)

Attachment: 1.patch
Description: Binary data

_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits

Reply via email to