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?
In C++17 this is called structured bindings, which allows for the following:
For the specific case of
std::tuple
(orstd::pair
) objects, C++ offers thestd::tie
function which looks similar:I am not aware of an approach to the notation exactly as you present it.
Mostly there with
std::map
andstd::tie
:Another possibility could be done as
which would be used like:
yielding local variables of
foo
andbar
.Of course it's limited to creating variables all of the same type, although I suppose you could use
auto
to get around that.And that macro is limited to doing exactly two variables. So you would have to create DESTRUCTURE3, DESTRUCTURE4, and so on to cover as many as you want.
I don't personally like the code style this ends up with, but it comes reasonably close to some of the aspects of the JavaScript feature.
I am afraid you cannot have it the way you are used to in JavaScript (which by the way seems to be new technology in JS). The reason is that in C++ you simply cannot assign to multiple variables within a structure/object/assignment expression as you did in
and then use
species
andsound
as simple variables. Currently C++ simply does not have that feature.You could assign to structures and/or objects whilst overloading their assignment operator, but I don't see a way how you could emulate that exact behaviour (as of today). Consider the other answers offering similar solutions; maybe that works for your requirement.