Code Bug Fix: Structure binding doesn’t work without type?

Original Source Link

I try to do something like this

pair<int, int> f() {
    return {1, 2};

int a, b;
[a, b] = f();

and get compilation error. All errors boil down to that fact, that the compiler think that it is a syntactically incorrect lambda. So if I use structured binding I always should write auto?

Yes, that’s just how structured bindings work. It introduces new identifiers, so they cannot be existing variables. So when using it, you must use auto, e.g.

auto [a, b] = f();   // can also be auto&, auto const, etc

If you want to use existing variables, you can use std::tie:

int a, b;
std::tie(a, b) = f();

Note that all the identifiers must be new, so you can’t mix and match these 2 approaches. e.g. you can’t use a structured binding with a single already existing variable.

Tagged : / /

Leave a Reply

Your email address will not be published. Required fields are marked *