8
votes

I skimmed through the paper on structured bindings here http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0144r0.pdf but I was not able to get a good sense of which types of structs the syntax allows binding to. My best guess is that the struct has to be an aggregate type. Or something with only public data members.

Is there any caveat I am missing to this?

1
Pairs and tuples seem like good examples, and map node types.Kerrek SB
@KerrekSB :) yeah I understand, I was just looking to understand a bit more about the details of which types of structs they can bind to, if for example I have my own struct.Curious
Sure. If you don't want to rely on public members, you can for example specialize std::get and std::tuple_size for your type.Kerrek SB
"Aggregates" are about initialization, not layout. You probably want some condition closer to that of "standard layout" (although indeed you need all members to be public, not just have the same access level).Kerrek SB
@KerrekSB ah yes, I did not think of specializing std::get and std::tuple_size. Although I am not sure if that is enough to ensure that the structured binding syntax would work for any class/struct.Curious

1 Answers

5
votes

If you don't want to specialize std::tuple_size, std::tuple_element and get for your type, then [dcl.decomp] requires:

Otherwise, all of E’s non-static data members shall be public direct members of E or of the same unambiguous public base class of E, E shall not have an anonymous union member, and the number of elements in the identifier-list shall be equal to the number of non-static data members of E.

So essentially all data members need to be declared in the same class, and they all need to be public, and you need to provide the same number of names as there are members.