Structured bindings have been introduced with c++17. They give the ability to declare multiple variables initialised from a tuple or struct.
This code compiles using a c++17
compiler.
#include <iostream>
#include <tuple>
int main() {
auto tuple = std::make_tuple(1.0, 1);
auto [ d, i ] = tuple;
std::cout << "d=" << d << " i=" << i << '\n';
return 0;
}
If I don't declare the variables with auto
I get the error
error: expected body of lambda expression [d2 , i2] = tuple;
#include <iostream>
#include <tuple>
int main() {
auto tuple = std::make_tuple(1.0, 2);
double d2;
int i2;
[d2 , i2] = tuple;
return 0;
}
I used clang version 4.0.0
and the compile option -std=c++1z
.
Can I assign existing variables to a structured binding? Do I need to use auto
?