10

I'm trying to loop over a vector of tuples:

std::vector<std::tuple<int, int, int>> tupleList;

By using a range based for loop with structured bindings:

for (auto&& [x, y, z] : tupleList) {}

But Visual Studio 2017 15.3.5 gives the error:

cannot deduce 'auto' type (initializer required)

But the following does work:

for (auto&& i : tupleList) {
    auto [x, y, z] = i;
}

Why is that?

Eejin
  • 770
  • 1
  • 8
  • 29
  • Why are you using `&&` and not `&`? – Charles Oct 04 '17 at 18:32
  • 1
    @Charles `&&` will work even if elements are const or temporaries – Guillaume Racicot Oct 04 '17 at 18:39
  • 8
    VS bug, it should work. Was even one of the motivations of the language feature (iterating over a map)! – Barry Oct 04 '17 at 18:40
  • Would `const auto` be ok as well? @GuillaumeRacicot – Charles Oct 04 '17 at 18:56
  • 3
    @Charles in that case, you won't be able to mutate elements, or forward them to a function that either take a const reference or a mutable reference. The thing is, `auto&&` simply works, and works everywhere, even in fully generic code. – Guillaume Racicot Oct 04 '17 at 19:01
  • @Charles `for (auto&& a : ..)` even has its own very standard proposal for a shortcut to `for (a : ..)` exploiting its universality. Refused though IIRC. – v.oddou Jun 22 '20 at 07:21

1 Answers1

14

It does work, but the intellisense doesn't use the same compiler: enter image description here

So even with the red lines and error shown in the editor it does compile with the ISO C++17 Standard (/std:c++17) switch.

I compiled the following program:

#include <vector>
#include <tuple>

std::vector<std::tuple<int, int, int>> tupleList;
//By using a range based for loop with structured bindings :

int main()
{
    for(auto&&[x, y, z] : tupleList) {}
}

Visual Studio version:

Microsoft Visual Studio Community 2017 Preview (2) Version 15.4.0 Preview 3.0 VisualStudio.15.Preview/15.4.0-pre.3.0+26923.0

cl version:

19.11.25547.0

From command line:

>cl test.cpp /std:c++17
Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25547 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
C:\Program Files (x86)\Microsoft Visual Studio\Preview\Community\VC\Tools\MSVC\14.11.25503\include\cstddef(31): warning C4577: 'noexcept' used with no exception handling mode specified; termination on exception is not guaranteed. Specify /EHsc
Microsoft (R) Incremental Linker Version 14.11.25547.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj
wally
  • 10,717
  • 5
  • 39
  • 72