【问题标题】:Auto range based structured bindings with vector基于自动范围的结构化绑定与向量
【发布时间】:2017-10-04 18:28:59
【问题描述】:

我正在尝试遍历元组向量:

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

通过使用基于范围的 for 循环和结构化绑定:

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

但是 Visual Studio 2017 15.3.5 给出了错误:

无法推断“自动”类型(需要初始化器)

但以下方法确实有效:

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

为什么会这样?

【问题讨论】:

  • 你为什么用&amp;&amp;而不是&amp;
  • @Charles &amp;&amp; 即使元素是 const 或 temporaries 也会起作用
  • VS 错误,它应该可以工作。甚至是语言功能的动机之一(迭代地图)!
  • const auto 也可以吗? @GuillaumeRacicot
  • @Charles 在这种情况下,您将无法改变元素,或将它们转发给采用 const 引用或可变引用的函数。问题是,auto&amp;&amp; 可以正常工作,并且可以在任何地方工作,即使是在完全通用的代码中也是如此。

标签: c++ c++17 structured-bindings


【解决方案1】:

它确实有效,但智能感知不使用相同的编译器:

因此,即使编辑器中显示红线和错误,它也可以使用ISO C++17 Standard (/std:c++17) 开关进行编译。

我编译了以下程序:

#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 预览版 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多