解构 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()::&’
有没有办法做到这一点?