8

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?

6
  • Pairs and tuples seem like good examples, and map node types.
    – Kerrek SB
    Dec 1, 2016 at 2:32
  • @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
    Dec 1, 2016 at 2:33
  • 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
    Dec 1, 2016 at 2:35
  • "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
    Dec 1, 2016 at 2:36
  • @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
    Dec 1, 2016 at 2:40

1 Answer 1

5

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.

2
  • Maybe this is gcc/clang bug/lack of proper implementation, but both compiler requires from the struct to be copyable - I mean have copy constructor. Can you comment on this? I can ask this as a question if you think it is worth to have this Q/A docummented?
    – PiotrNycz
    Jan 19, 2017 at 16:43
  • @PiotrNycz: I suggest you wait until C++17 has been published; then it would make an excellent question.
    – Kerrek SB
    Jan 19, 2017 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.