Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I emulate destructuring in C++?

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?

like image 448
Trevor Hickey Avatar asked Jul 13 '15 22:07

Trevor Hickey


People also ask

What is the syntax for object Destructuring?

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.

Can you Destructure an array?

You can destructure an array more than once in the same code snippet.

How do you Destructure an array of objects?

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.

Can you Destructure nested object?

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 .


2 Answers

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"; } 
like image 105
dalle Avatar answered Sep 21 '22 21:09

dalle


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.

like image 30
Escualo Avatar answered Sep 22 '22 21:09

Escualo