首页 > 解决方案 > 在 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()::&’

有没有办法做到这一点?

标签: c++c++17destructuringstd-pairstructured-bindings

解决方案


有没有办法在隐藏现有变量的同时解构一对?

不。结构化绑定声明总是引入标识符,它不能隐藏或分配现有变量。这是格式错误的:

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这在这种情况下有效,但不适用于可能返回具有两个公共成员的结构的一般情况。


推荐阅读