Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c++ - structured bindings: when something looks like a reference and behaves similarly to a reference, but it's not a reference

Yesterday I've seen an interesting question here on SO about structured binding.
We can sum up it as it follows. Consider the example code below:

#include <tuple>
#include <type_traits>

int main() {
    auto tup = std::make_tuple(1, 2);
    auto & [ a, b ] = tup;
    // the following line won't compile for a isn't a reference
    // static_assert(std::is_reference_v<decltype(a)>);
}

In this case decltype(a) is int (probably) because of this bullet (working draft):

if e is an unparenthesized id-expression naming a structured binding [...], decltype(e) is the referenced type as given in the specification of the structured binding declaration

Here is a snippet on wandbox provided by @Curious in the comments for those that are interested. It shows that actually a isn't a reference, nothing more.
So far so good for the original question, OP asked why it was int instead of int & and the standard says that looked like an acceptable answer.

Anyway, I'd like to know why the committee decided so. At the end of the day, a refers to an element in the tuple and I can modify that element through a. In other terms, the declaration of a looks like the one of a reference, it behaves similarly to a reference but it's not a reference.

I can live with this, but I'd like to know what are the reasons behind that. Why decltype(a) cannot be simply int &? Is there a meaningful reason that a profane can understand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote this yesterday:

decltype(x), where x is a structured binding, names the referenced type of that structured binding. In the tuple-like case, this is the type returned by std::tuple_element, which may not be a reference even though the structured binding itself is in fact always a reference in this case. This effectively emulates the behavior of binding to a struct whose non-static data members have the types returned by tuple_element, with the referenceness of the binding itself being a mere implementation detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...