C++ 具有结构化绑定的不同cv限定符

C++ 具有结构化绑定的不同cv限定符,c++,c++17,C++,C++17,C++17中的支持多种不同的选项,例如: std::tuple<int, int> foo(); auto [a, b] = foo(); // a and b are: int const auto [a, b] = foo(); // a and b are: int const const auto& [a, b] = foo(); // a and b are: int const& std::tuple foo(); auto[a,b]=foo();

C++17中的支持多种不同的选项,例如:

std::tuple<int, int> foo();

auto  [a, b] = foo(); // a and b are: int
const auto  [a, b] = foo(); // a and b are: int const
const auto& [a, b] = foo(); // a and b are: int const&
std::tuple foo();
auto[a,b]=foo();//a和b是:int
const auto[a,b]=foo();//a和b是:int常量
常量auto&[a,b]=foo();//a和b是:int常量&

有没有办法给
a
b
不同的简历限定词?例如,
a
作为
int
b
作为
int const

否的类型-这在“问题与回答”中有介绍:

是否应该扩展语法以允许const/&限定单个名称的类型?

我们认为答案应该是否定的。这是一个存储值并将名称绑定到其组件的简单功能, 不要声明多个变量。允许这样的限定将是特性蠕变,将特性扩展到 可以使用不同的方法,即声明多个变量的方法。 如果我们确实想声明多个变量,我们已经有了一种拼写方法:

auto val = f(); // or auto&&
T1& x = get<0>(val);
T2 const y = get<1>(val);
T3 const& z = get<2>(val);
auto val=f();//或自动&&
T1&x=get(val);
T2 const y=get(val);
T3常数&z=get(val);

这是不允许的,但似乎对结构化绑定的工作原理存在一些误解。以下是代码段的实际工作方式:

std::tuple<int, int> foo();

auto  [a, b] = foo(); // `a` and `b` are `int`
auto& [a, b] = foo(); // error: cannot bind a non-const lvalue-ref to an rvalue.
const auto  [a, b] = foo(); // `a` and `b` are: `int const`
const auto& [a, b] = foo(); // `a` and `b` are: `int const`! (NOT `int const&`)
                            // lifetime extension of `foo()` via `const&`.
这与以下情况相反:

auto&& temp = foo();  // save `temp` like range-based `for` does!
// if `auto` in `auto [a, b]` were distributive.
auto a = std::get<0>(temp);
auto b = std::get<1>(temp);
auto&&temp=foo();//保存'temp'类似基于范围的'for'does!
//如果'auto[a,b]`中的'auto'是分布的。
自动a=标准::获取(温度);
自动b=标准::获取(温度);

Ok。不幸的是,<代码> Val仍然在范围内。根据哪个情况更需要,可以考虑用不同的CV限定符来定义元组。
auto temp = foo();  // `auto` is for the initializer!
// These aren't actually references, but close.
auto&& a = std::get<0>(temp);
auto&& b = std::get<1>(temp);
auto&& temp = foo();  // save `temp` like range-based `for` does!
// if `auto` in `auto [a, b]` were distributive.
auto a = std::get<0>(temp);
auto b = std::get<1>(temp);