2017-10-04 42 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