Consider the following struct that contains some environment values:
struct environment_values {
uint16_t humidity;
uint16_t temperature;
uint16_t charging;
};
I would like to add some additional information to those values with a phantom type* and make their types distinct at the same time:
template <typename T, typename P>
struct Tagged {
T value;
};
// Actual implementation will contain some more features
struct Celsius{};
struct Power{};
struct Percent{};
struct Environment {
Tagged<uint16_t,Percent> humidity;
Tagged<uint16_t,Celsius> temperature;
Tagged<uint16_t,Power> charging;
};
Is the memory-layout of Environment
the same as environment_values
? Does this also hold for mixed type layouts, e.g.:
struct foo {
uint16_t value1;
uint8_t value2;
uint64_t value3;
}
struct Foo {
Tagged<uint16_t, Foo> Value1;
Tagged<uint8_t , Bar> Value2;
Tagged<uint64_t, Quux> Value3;
}
For all types I've tried so far, the following assertions held:
template <typename T, typename P = int>
constexpr void check() {
static_assert(alignof(T) == alignof(Tagged<T,P>), "alignment differs");
static_assert(sizeof(T) == sizeof(Tagged<T,P>), "size differs");
}
// check<uint16_t>(), check<uint32_t>(), check<char>() …
Since the size of the tagged and untagged variants is also the same, I guess the answer should be yes, but I would like to have some certainty.
* I have no idea how those tagged values are called in C++. "Strongly typed typedefs"? I've taken the name from Haskell.
struct { T m; }
andT
are layout-compatible. – Freestyle