C++17 destructuring bind

I know very little about C++17, but I attended a talk about it this morning and the syntax for destructuring bind caught my attention.

This is a feature widely supported in other languages, where you assign a complex type to another complex declaration with individual names in it that match the original type, and you can then refer individually to the values that were assigned.

Python:

>>> [a,b,c] = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>>

Standard ML (is that the Ur-language here?):

> val (a, b) = (1, 2);
val a = 1: int
val b = 2: int
> val { this, that } = { that = 1, this = 2 };
val that = 1: int
val this = 2: int

In C++17 the target syntax uses square brackets:

int a[2] = {1,2};
auto [x,y] = a;

It works regardless of whether the source is a structure, array, tuple, pair, etc.

What is interesting about it, in C++, is that it appears the source structure is always indexed by declaration order, rather than by name. That is, if you write

struct { int a; int b; } x { 1, 2 };
auto [b, a] = x;

then b will be 1 and a will be 2, even though in the original structure b was 2 and a was 1.

In other languages, a destructuring bind of a structure with named fields is performed using matching by name rather than by index. (See the SML example above.)

This highlights something that has been building for a while about C++. Since C++11 introduced the structure initialisation syntax in which you just list structure values one by one, we have increasingly accepted referring to structure elements by declaration order rather than by name. Someone who swapped two structure elements of the same type could break an awful lot of code without the compiler noticing. This doesn’t feel very safe, for a supposedly type-safe (ish) language.

And it isn’t the way other languages work. I don’t know any other language that will happily destructure a named structure by index rather than name, or even construct one (even the structure initialisers in C, since C99, are safer).

I’d love to know whether this has affected many people in practice, or whether I’m just being a bit suspicious.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s