2017-10-04 41 views
9

我試圖遍歷元組的載體:自動量程基礎結構綁定與矢量

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

通過使用基於for循環與結構綁定一個範圍:

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

但Visual Studio中2017年15.3.5給出了錯誤:

cannot deduce 'auto' type (initializer required)

但下面不工作:

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

這是爲什麼?

+0

爲什麼你使用'&&'而不是'&'? – Charles

+0

@Charles'&&'即使元素是常量或臨時值也可以工作 –

+6

VS錯誤,它應該工作。甚至是語言功能的動機之一(遍歷地圖)! – Barry

回答

14

它的工作,但智能感知不使用相同的編譯器:在它與ISO C++17 Standard (/std:c++17)開關編譯編輯器中顯示的紅線和錯誤因此,即使 enter image description here

我整理了以下程序:

#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版本:

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版本:

19.11.25547.0

從命令行:

>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