c++ - 在 C++ 中解构时如何隐藏现有变量?
问题描述
解构 a 时有没有办法隐藏现有变量std::pair
?例如,如果我定义了以下函数:
#include <iostream>
#include <utility>
std::pair<int, int> returns_pair(int a, int b)
{
return std::make_pair(a * a, b * b);
}
void prints_two_variables(int a, int b)
{
std::cout << a << "\n" << b << "\n";
}
然后这个main
函数工作正常,因为我从返回的新变量std::pair
:
int main()
{
int a = 2;
int b = 3;
auto [x, y] = returns_pair(a, b);
prints_two_variables(x, y);
return 0;
}
输出:
4 9
但我不能使用相同的变量名并隐藏现有变量,因为这会尝试再次实际声明它们:
int main()
{
int a = 2;
int b = 3;
auto [a, b] = returns_pair(a, b);
prints_two_variables(a, b);
return 0;
}
错误:
main.cpp: In function ‘int main()’: main.cpp:12:15: error: conflicting declaration ‘auto a’ auto [a, b] = returns_pair(a, b); ^ main.cpp:10:9: note: previous declaration as ‘int a’ int a = 2; ^ main.cpp:12:15: error: conflicting declaration ‘auto b’ auto [a, b] = returns_pair(a, b); ^ main.cpp:11:9: note: previous declaration as ‘int b’ int b = 3; ^
我也试过没有auto
,但这给出了一个完全不同的错误:
int main()
{
int a = 2;
int b = 3;
[a, b] = returns_pair(a, b);
prints_two_variables(a, b);
return 0;
}
错误:
main.cpp: In lambda function: main.cpp:12:12: error: expected ‘{’ before ‘=’ token [a, b] = returns_pair(a, b); ^ main.cpp: In function ‘int main()’: main.cpp:12:31: error: no match for ‘operator=’ (operand types are ‘main()::’ and ‘std::pair’) [a, b] = returns_pair(a, b); ^ main.cpp:12:10: note: candidate: main()::& main()::::operator=(const main()::&) [a, b] = returns_pair(a, b); ^ main.cpp:12:10: note: no known conversion for argument 1 from ‘std::pair’ to ‘const main()::&’
有没有办法做到这一点?
解决方案
有没有办法在隐藏现有变量的同时解构一对?
不。结构化绑定声明总是引入标识符,它不能隐藏或分配现有变量。这是格式错误的:
int i = 4;
auto [i] = std::tuple(5);
出于同样的原因,这是格式错误的:
int i = 4;
int i = 5;
如果你想做的是覆盖,你可以使用tie
和分配:
std::tie(a, b) = returns_pair(a, b);
returns_pair
这在这种情况下有效,但不适用于可能返回具有两个公共成员的结构的一般情况。
推荐阅读
- ssl-certificate - 如何从 gcloud 设置 SSL 证书?
- python-3.x - 无法在 Pycharm 中访问 Python 中的环境变量
- json - 如何在 servlet 中读取 json 值?
- python - 如何使用python绘制多个子图
- swift - 如何通知一个目标的获取结果控制器另一个目标的托管对象上下文中发生的更改?
- c# - 是否可以在 HTML 帮助器方法中确定 ASP.NET Core 托管环境?
- php - 如何从单选按钮中一一提交选择的答案
- linux - 构建一个查找目录中所有文件的 UNIX 管道(使用 find 、xargs 和 du 命令)
- c# - 仅在存在时选择类相关数据
- android - 使用 Retrofit 和 OkHttp 显示没有 Internet 连接对话框