我正在尝试使用结构化绑定更新传递给函数的变量:
#include <iostream>
#include <tuple>
#include <utility>
std::pair<int, double> func(double y)
{
return {1, 1.3+y};
}
int main() {
double y = 1.0;
auto [x, y2] = func(y);
y = y2;
std::cout << "x = " << x << ", y = " << y << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是否有可能避免额外的分配y = y2并使用类似的东西
[auto x, y] = func(y); // this does not work
Run Code Online (Sandbox Code Playgroud)
或者
std::tie(auto x, y) = func(y); // this does not work
Run Code Online (Sandbox Code Playgroud)
狭隘地回答你的问题:
不可以,您不能在结构化绑定中重用现有变量。结构化绑定总是声明新变量。
话虽这么说,还有其他选择 - 就像std::tie@Robert A 所演示的那样。
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |