2017-10-04 15 views
9

Tôi đang cố gắng để lặp qua một vector của các bộ:phạm vi Auto dựa bindings cấu trúc với vector

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

Bằng cách sử dụng một loạt dựa cho vòng lặp với các ràng buộc có cấu trúc:

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

Nhưng Visual Studio 2017 15.3.5 đưa ra lỗi:

cannot deduce 'auto' type (initializer required)

Nhưng những điều sau đây hoạt động:

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

Tại sao lại như vậy?

+0

Tại sao bạn sử dụng '&&' chứ không phải '&'? – Charles

+0

@Charles '&&' sẽ hoạt động ngay cả khi các phần tử là const hoặc temporaries –

+6

Lỗi VS, nó sẽ hoạt động. Thậm chí là một trong những động lực của tính năng ngôn ngữ (lặp qua bản đồ)! – Barry

Trả lời

14

Nó không làm việc, nhưng IntelliSense không sử dụng trình biên dịch giống nhau: enter image description here

Vì vậy, ngay cả với các đường màu đỏ và lỗi hiển thị trong trình soạn thảo nó biên dịch với ISO C++17 Standard (/std:c++17) switch.

tôi biên soạn chương trình sau đây:

#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 phiên bản:

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 phiên bản:

19.11.25547.0

Từ dòng lệnh:

>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 
Các vấn đề liên quan