26

Does MSVC10 support the C++0x draft standard's range based loop?

http://en.wikipedia.org/wiki/C%2B%2B0x#Range-based_for-loop

Example:

for (int& p : array) { ... }
MW_dev
  • 2,146
  • 1
  • 26
  • 40
  • 3
    MSVC10 implemented an earlier proposal, something like `for each (int& p in array)` should work – Ben Voigt Aug 01 '11 at 13:32
  • 1
    Looks like this is the documentation for what @BenVoigt mentions: [How to: Iterate Over STL Collection with for each](http://msdn.microsoft.com/en-us/library/ms177203.aspx). Looks like this was originally intended for C++/CLR code, and it also looks like it might not work with non-CLR arrays. – crashmstr Jul 11 '12 at 18:18
  • I assume this for_each (T& t in tt) will only work in VS2010 compiler? – paulm Jun 03 '13 at 08:30

2 Answers2

29

No. Stephan T. Lavavej's explains the feature was altered too late in Visual Studio 2010's release cycle.

Comments on the Visual Studio Team's blog: http://blogs.msdn.com/b/vcblog/archive/2009/07/13/intellisense-and-browsing-with-c-0x.aspx

MW_dev
  • 2,146
  • 1
  • 26
  • 40
6

It doesn't, but you can simulate it with a macro.

template<typename T>
struct false_wrapper
{
    false_wrapper(const T& value) : value(value) { }

    operator bool() const { return false; }

    T value;
};

template<typename T>
false_wrapper<T> make_false_wrapper(const T& value)
{
    return false_wrapper<T>(value);
}

template<typename T>
struct false_ref_wrapper
{
    false_ref_wrapper(T& value) : value(value) { }

    operator bool() const { return false; }

    T& value;

private:
    false_ref_wrapper& operator=(const false_ref_wrapper&);
};

template<typename T>
false_ref_wrapper<T> make_false_ref_wrapper(T& value)
{
    return false_ref_wrapper<T>(value);
}

template<typename T>
void increment(T& it)
{
    ++it;
}

#define foreach_(VAL, VALS) \
    if (auto _foreach_col = make_false_ref_wrapper(VALS)) { } else \
    if (auto _foreach_cur = make_false_wrapper(std::begin(_foreach_col.value))) { } else \
    if (auto _foreach_end = make_false_wrapper(std::end(_foreach_col.value))) { } else \
    for (bool _foreach_flag = true; \
              _foreach_flag && _foreach_cur.value != _foreach_end.value; \
              _foreach_flag ? increment(_foreach_cur.value) : (void) 0) \
        if ((_foreach_flag = false) == true) { } else \
        for (VAL = *_foreach_cur.value; !_foreach_flag; _foreach_flag = true)
Valentin Milea
  • 3,186
  • 3
  • 28
  • 29