【问题标题】:Are structured bindings reusable?结构化绑定是否可重用?
【发布时间】:2018-10-23 15:52:03
【问题描述】:

我使用的是 Windows 10、Visual Studio 2017 v15.7.1 和 /std:c++latest /permissive-

这个带有结构化绑定的简单代码无法编译:

auto [a, b] = func1(x, y, z); // auto func1() -> std::tuple<double, double, double>
[a, b] = func2(x, y, z); // same signature as func2

E1277 attributes are not allowed here

下面的代码也不能编译,同样的错误

double a, b;
[a, b] = func1(x, y, z);
[a, b] = func2(x, y, z);

代码

auto [a, b] = func1(x, y, z);
auto [a, b] = func2(x, y, z);

也不会编译,理所当然地抱怨重新定义。

它编译的唯一方法是

auto [a1, b1] = func1(x, y, z);
auto [a2, b2] = func2(x, y, z);

坦率地说,这很丑。

这个功能是这样设计的吗?还是VC++的bug?

【问题讨论】:

    标签: c++ visual-c++ language-lawyer c++17 structured-bindings


    【解决方案1】:

    结构化绑定必须具有auto。来自cppreference

    attr(optional) cv-auto ref-operator(optional) [ identifier-list ] = expression ;
    

    ...
    cv-auto - 可能是 cv 限定的类型说明符 auto
    ...

    省略变体;只需更改= expression 部分

    我们可以看到cv-auto是强制性的。


    如果要重新绑定ab,请使用std::tie

    auto [a, b] = func1(x, y, z);
    std::tie(a, b) = func2(x, y, z);
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2017-11-25
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多