11

I'm writing a class that, assuming the answer to Are enumeration types layout compatible with their underlying type? is "yes", is layout-compatible struct kevent but uses enum classes for filter, flags, etc. with the proper underlying types for the relevant fields. It is also standard-layout (the fields are all private and all themselves standard layout, there are no virtual members, there are no base classes). From my reading of n3690, I can determine that my class and struct kevent have the same value representation, but I can't see anything in the standard that therefore allows me to reinterpret_cast between them, even though that seems like the reasonable interpretation of "value representation". Is this technically allowed by the standard? If not, what does knowing the value representation of a type give you?

EDIT 2014/02/24 16:45 EST: In response to a comment, I should clarify that I want to reinterpret_cast the first class to a reference to the second, as of course you can't directly reinterpret_cast a non-pointer type to another non-pointer type.

Community
  • 1
  • 1
Shea Levy
  • 5,237
  • 3
  • 31
  • 42
  • 1
    [class.mem]/18 allows some type punning through unions, [class.mem]/19 allows accessing the *first* data member via a `reinterpret_cast`. But I'm not sure if there's more. – dyp Feb 22 '14 at 19:21
  • 1
    You can't `reinterpret_cast` between struct types, do you mean cast between pointers to those types and read one through a pointer to the other? – Jonathan Wakely Feb 24 '14 at 15:02
  • If you can `reinterpret_cast` from `pointer to A` to `pointer to B`, you can `reinterpret_cast` from `A` to `reference to B`. I'll update the question to explicitly mention the `reference to` bit. – Shea Levy Feb 24 '14 at 21:45

1 Answers1

12

but I can't see anything in the standard that therefore allows me to reinterpret_cast between them, even though that seems like the reasonable interpretation of "value representation". Is this technically allowed by the standard?

No. The standard is clear (see [basic.lval] p10) about which types can be aliased, and layout-compatible types are not included.

If not, what does knowing the value representation of a type give you?

If the types are both trivially copyable and have the same value representation then you could memcpy from an object of one type to an object of the other type, and vice versa. If they're not trivially copyable then it doesn't give you much at all.

AFAICT the standard doesn't actually say what can and can't be done with layout-compatible types.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521