In JavaScript ES6, there is a language feature known as destructuring. It exists across many other languages as well.
In JavaScript ES6, it looks like this:
var animal = { species: 'dog', weight: 23, sound: 'woof' } //Destructuring var {species, sound} = animal //The dog says woof! console.log('The ' + species + ' says ' + sound + '!')
What can I do in C++ to get a similar syntax and emulate this kind of functionality?
By writing var name = hero.name , you have to mention the name binding 2 times, and the same for realName . That's where the object destructuring syntax is useful: you can read a property and assign its value to a variable without duplicating the property name.
You can destructure an array more than once in the same code snippet.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.
Nested Object and Array Destructuring Here's another example with an array of objects: You can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .
In C++17 this is called structured bindings, which allows for the following:
struct animal { std::string species; int weight; std::string sound; }; int main() { auto pluto = animal { "dog", 23, "woof" }; auto [ species, weight, sound ] = pluto; std::cout << "species=" << species << " weight=" << weight << " sound=" << sound << "\n"; }
For the specific case of std::tuple
(or std::pair
) objects, C++ offers the std::tie
function which looks similar:
std::tuple<int, bool, double> my_obj {1, false, 2.0}; // later on... int x; bool y; double z; std::tie(x, y, z) = my_obj; // or, if we don't want all the contents: std::tie(std::ignore, y, std::ignore) = my_obj;
I am not aware of an approach to the notation exactly as you present it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With