How can I emulate destructuring in C++?
Solution 1:
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";
}
Solution 2:
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.
Solution 3:
Mostly there with std::map
and std::tie
:
#include <iostream>
#include <tuple>
#include <map>
using namespace std;
// an abstact object consisting of key-value pairs
struct thing
{
std::map<std::string, std::string> kv;
};
int main()
{
thing animal;
animal.kv["species"] = "dog";
animal.kv["sound"] = "woof";
auto species = std::tie(animal.kv["species"], animal.kv["sound"]);
std::cout << "The " << std::get<0>(species) << " says " << std::get<1>(species) << '\n';
return 0;
}