Often, we'll have a struct, and we'll want to extract all of its members to standalone variables:
void SomeFunction(Vector3 SomeVector) {
float a { SomeVector.x };
float b { SomeVector.y };
float c { SomeVector.z };
// ...
}
C++ offers a convenient shortcut to this, called structured binding.
Those with experience in other programming languages may already be familiar with this concept. Other common names for it include destructuring and deconstructing.
The C++ syntax looks like this:
void SomeFunction(Vector3 SomeVector) {
auto [a, b, c] { SomeVector };
// ...
}
To break this down, first we declare the type of our new variables. When we're creating variables using structured binding, we need to use the keyword auto
here.
As we covered in the previous lesson, this asks the compiler to figure out what the type of each variable is. With structured binding, we must use auto, even if all our variables have the same underlying type.
After auto
, we open up a set of square brackets - [
and ]
. Within these brackets, we specify the name we want to use for each variable we create.
Finally, we provide the struct we want to use to initialise these variables.
The above code will set a
, b
and c
to be the first, second and third public members of our struct, respectively.
Because structs and classes are almost the same, we can also use destructuring with our classes, as long as the variables are public:
class Character {
public:
string Name { "Goblin Warrior" };
int Level { 5 };
int Health { 100 };
}
Character MyCharacter;
auto [
CharacterName,
CharacterLevel,
CharacterHealth
] { MyCharacter };
Out of the box, structured binding might seem a bit limited. For example, to use it, we need to create a variable for every public member of our object, even if we only want the first few.
This is likely to make it useless for larger classes. However, we do have the ability to overload the structured binding operators, to let us take control of the behaviour.
Overloading structured binding is a bit more complicated than the examples we've previously seen. It also relies on a few new concepts that are out of the scope of a beginner course, but we cover it in the next course.
For now though, it's still useful when working with simple structs like our Vector3
.
Additionally, even with a basic familiarity with the concept, when we see auto [...]
in other code, we'll have some intution as to what's happening.
With our new knowledge of all things struct, lets move onto the next lesson!
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way