How can I emulate destructuring in C++?

Trevor Hickey picture Trevor Hickey · Jul 14, 2015 · Viewed 8.9k times · Source

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?

Answer

dalle picture dalle · Dec 1, 2016

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";
}