结构绑定和变量类型 [英] Structural binding and type of variables
问题描述
我想问一个关于结构绑定以及变量如何获取其类型的问题。
这是我编译的代码。
I would like to ask a question about structural binding and how the variables get their types. Here is the code I compile.
struct T {
explicit T(int a = 1) {
a_ = a;
std::cout << "Default" << std::endl;
}
T(const T& t) {
a_ = t.a_;
std::cout << "Copy" << std::endl;
}
int a_;
};
int main() {
std::tuple<bool, T> bi{true, T(1)};
std::cout << "START" << std::endl;
auto& [b, i] = bi;
static_assert(std::is_same<decltype(i), T>::value);
std::cout << i.a_ << std::endl;
i.a_++;
std::cout << i.a_ << std::endl;
std::cout << (&i == &get<1>(bi)) << std::endl;
return 0;
}
代码会编译,结果是:
Default
Copy
START
1
2
1
您可以看到变量 i
实际上是指得到< 1>(bi)
。
但是,变量 i
的类型是 T
,因为 std :: is_same< decltype(i),T> :: value
。
您能否解释一下为什么结构绑定如此工作?
我已经在 C ++模板:完整指南书中读过
,作者指出变量 i
必须具有类型 std :: tuple_element< 1,std :: tuple< bool,T> > :: type&
。我不明白为什么 decltype(i)
只是 T
。
As you can see the variable i
actually refers to get<1>(bi)
.
However, the type of the variable i
is T
since std::is_same<decltype(i), T>::value
.
Could you please explain why structural binding works this way?
I have read about it in the book "C++ Templates: The Complete Guide"
and the authors state that the variable i
must have type std::tuple_element<1, std::tuple<bool, T> >::type&&
. I don't understand why decltype(i)
is just T
.
推荐答案
decltype
很有趣。其规范包含用于结构化绑定的特殊条款
decltype
is funny that way. Its specification contains a special clause for structured bindings
4 对于表达式
e
,用表示的类型decltype(e)
是
,定义如下:
4 For an expression
e
, the type denoted bydecltype(e)
is defined as follows:
-
如果
e
是未括号的id表达式,命名为结构化绑定([dcl.struct.bind]),decltype(e)
被引用类型为结构化绑定声明的规范中给出的
;
if
e
is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]),decltype(e)
is the referenced type as given in the specification of the structured binding declaration;
...
因此,尽管每个结构化绑定确实是对元组的引用,但 decltype
报告引用对象的类型。可能是因为结构化绑定的意思是像常规命名变量一样。
So while each structured binding is indeed a reference into the tuple, decltype
reports the type of the referent. Likely since structured bindings are meant to feel like regular named variables.
这篇关于结构绑定和变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!