1

Visual Studio 2017 claims that they support C++17 range based for loops. However when I try to compile I get errors indicating that it is using the C++11 style. Has anyone managed to get sentinel loops working in VS 2017?

Here is some example code. I've gutted this code to make it short, so it obviously won't work properly, but it should compile.

struct MyExampleIterator
{
    int operator*() const { return 0; }

    MyExampleIterator& operator++() { return *this; }
};

class MyExampleSentinel {};

bool operator!=(const MyExampleIterator& a, const MyExampleSentinel& b) { return true; }

struct MyExampleRange
{
    MyExampleIterator begin() { return MyExampleIterator(); }
    MyExampleSentinel end() { return MyExampleSentinel(); }
};

If I try to use this class in a range based for loop in VS2017 (15.2) I get error C3538: in a declarator-list 'auto' must always deduce to the same type

MyExampleRange range;
for (auto i : range) {} // error C3538

But if I manually construct the C++17 standard code it compiles fine:

// Compiles fine
MyExampleRange range;
{
    auto && __range = range;
    auto __begin = __range.begin();
    auto __end = __range.end();
    for (; __begin != __end; ++__begin) {
        auto i = *__begin;
    }
}
3
  • Your example compiles for me on whatever version is on godbolt (19.10.25017?) So maybe 15.2 isn't new enough? Commented May 1, 2018 at 18:12
  • Can't test right now, but current is 15.6.x, not 15.2, so it's possible it got fixed in one of the service releases. Commented May 1, 2018 at 18:13
  • Compiles on 15.6.7 (and runs forever when != is always true). Commented May 1, 2018 at 18:56

1 Answer 1

1

The problem was that while I was using VS2017 the project was still targeted to VS2015. After retargeting to 2017 it compiles fine.

Thanks for the help. The reports that it compiles in 15.6 made me start digging for other answers once I updated to 15.6 and it still didn't compile. Thanks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.