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&
Run Code Online (Sandbox Code Playgroud)
有没有什么办法让a和b不同的CV-预选赛?例如aas int和bas 的类型int const?
不 - 这在提案的问答中有所涉及:
是否应该扩展语法以允许const /& - 限定个人姓名的类型?
Run Code Online (Sandbox Code Playgroud)auto [& x, const y, const& z] = f(); // NOT proposed我们认为答案应该是否定的.这是一个简单的功能,用于存储值并将名称绑定到其组件,而不是声明多个变量.允许这样的限定将是特征蠕变,将特征扩展为不同的东西,即声明多个变量的方式.如果我们确实要声明多个变量,我们已经有了拼写它的方法:
Run Code Online (Sandbox Code Playgroud)auto val = f(); // or auto&& T1& x = get<0>(val); T2 const y = get<1>(val); T3 const& z = get<2>(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&`.
Run Code Online (Sandbox Code Playgroud)
基于您给出的示例,似乎错误在于认为autoin auto [a, b] 分布在变量之间.它不是.该auto居然还有初始化的类型.在C++中,这大致编码如下:
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);
Run Code Online (Sandbox Code Playgroud)
这与以下内容相反:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |