const 上的结构化绑定
Structured binding on const
下面的代码可以编译吗?
#include <type_traits>
void foo() {
const std::pair<int, int> x = {1, 2};
auto [a, b] = x;
static_assert(std::is_const_v<decltype(a)>);
static_assert(std::is_const_v<decltype(b)>);
}
那么,这是 MSVC 错误吗?
这里的标准并不简单(我快速浏览了一下),但考虑到 auto
的规则,我想,a
和 b
应该被复制并丢弃 cv-限定词.
Is the following code supposed to compile?
不是。这是一个 MSVC 错误。
A structured binding declaration 引入了一个新名称(仅用于规范),e
,声明如下:
auto e = x;
e
的类型称为 E
,由于初始化器是类似元组的,绑定的类型由 tuple_element_t<i, E>
. In this case E
is pair<int, int>
, so the two types are just int
. The rule for decltype
of a structured binding is to give the referenced type 给出,所以 decltype(a)
和 decltype(b)
都是 int
。
这里的重要部分是a
和b
(结构化绑定)来自发明的变量(e
),而不是 它的初始值设定项 (x
)。 e
不是 const
因为你刚刚声明了它 auto
。我们正在做的是复制 x
,然后将绑定放入此(非 const
)副本中。
代码中的静态断言应该失败。为什么?因为你的代码和情况基本一样:
#include <type_traits>
void foo() {
const int x_1 = 1;
const int x_2 = 2;
auto a = x_1;
auto b = x_2;
static_assert(std::is_const_v<decltype(a)>);
static_assert(std::is_const_v<decltype(b)>);
}
在 C++ 中,表达式类型在赋值时衰减 :auto
看到 int
,而不是 const int
。结构化绑定只允许您一次执行多个 auto
绑定。
...所以 MSVC 不会在您的代码中的断言上失败这一事实似乎是一个错误。
下面的代码可以编译吗?
#include <type_traits>
void foo() {
const std::pair<int, int> x = {1, 2};
auto [a, b] = x;
static_assert(std::is_const_v<decltype(a)>);
static_assert(std::is_const_v<decltype(b)>);
}
那么,这是 MSVC 错误吗?
这里的标准并不简单(我快速浏览了一下),但考虑到 auto
的规则,我想,a
和 b
应该被复制并丢弃 cv-限定词.
Is the following code supposed to compile?
不是。这是一个 MSVC 错误。
A structured binding declaration 引入了一个新名称(仅用于规范),e
,声明如下:
auto e = x;
e
的类型称为 E
,由于初始化器是类似元组的,绑定的类型由 tuple_element_t<i, E>
. In this case E
is pair<int, int>
, so the two types are just int
. The rule for decltype
of a structured binding is to give the referenced type 给出,所以 decltype(a)
和 decltype(b)
都是 int
。
这里的重要部分是a
和b
(结构化绑定)来自发明的变量(e
),而不是 它的初始值设定项 (x
)。 e
不是 const
因为你刚刚声明了它 auto
。我们正在做的是复制 x
,然后将绑定放入此(非 const
)副本中。
代码中的静态断言应该失败。为什么?因为你的代码和情况基本一样:
#include <type_traits>
void foo() {
const int x_1 = 1;
const int x_2 = 2;
auto a = x_1;
auto b = x_2;
static_assert(std::is_const_v<decltype(a)>);
static_assert(std::is_const_v<decltype(b)>);
}
在 C++ 中,表达式类型在赋值时衰减 :auto
看到 int
,而不是 const int
。结构化绑定只允许您一次执行多个 auto
绑定。
...所以 MSVC 不会在您的代码中的断言上失败这一事实似乎是一个错误。