【发布时间】:2020-01-24 16:58:41
【问题描述】:
我认为使用结构化绑定和auto& 说明符我可以获得对结构成员的引用并直接使用它们而不是通过结构。
但是,以下代码有效并且静态断言成立:
struct Test
{
int i;
char c;
double d;
};
Test test{ 0, 1, 2 };
auto& [i, c, d] = test;
i = 4;
c = 5;
d = 6;
// i, c, d are not references !
static_assert(!std::is_same_v<decltype(i), int&>);
static_assert(!std::is_same_v<decltype(c), char&>);
static_assert(!std::is_same_v<decltype(d), double&>);
cout << &i << " == " << &test.i << " (" << std::boolalpha << (&i == &test.i) << ")" << endl; // (true)
cout << test.i << ", " << (int)test.c << ", " << test.d << endl; // 4, 5, 6
但我认为 C++ 不允许一个变量有多个名称,除非一个是真实变量,而其他变量是引用,但在这种情况下,变量 i 与 test.i 相同,两者都不是是参考。
【问题讨论】:
-
i是您显示的代码中的引用。auto& [i ...- 这是一个参考。 -
如果两个变量的作用域不同,它确实允许这样做。
标签: c++ c++17 structured-bindings