Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ekpyron/f714b40d014716d1efe0da2bc307afd4 to your computer and use it in GitHub Desktop.
Save ekpyron/f714b40d014716d1efe0da2bc307afd4 to your computer and use it in GitHub Desktop.
#include <type_traits>
#include <cassert>
enum class StructureType {
A, B, C
};
template<StructureType fixedType>
class alignas(StructureType) FixedStructureType {
StructureType value = fixedType;
};
struct A {
FixedStructureType<StructureType::A> sType;
int a = 42;
int b = 23;
};
struct Reference {
StructureType s;
int a;
int b;
};
static_assert(std::is_standard_layout_v<A>, "");
static_assert(sizeof(A) == sizeof(Reference), "");
static_assert(alignof(A) == alignof(Reference), "");
static_assert(std::is_aggregate_v<A>, "");
int main() {
{
A a{{}, 1, 2};
assert(reinterpret_cast<Reference const*>(&a)->s == StructureType::A);
assert(a.a == 1);
assert(a.b == 2);
}
{
A a{{}, 1};
assert(reinterpret_cast<Reference const*>(&a)->s == StructureType::A);
assert(a.a == 1);
assert(a.b == 23);
}
// A a({}, 1, 2); // should compile, once C++20 support is implemented in the compilers
// A a({}, 1); // should compile, once C++20 support is implemented in the compilers
{
A a{.a = 1, .b = 2};
assert(reinterpret_cast<Reference const*>(&a)->s == StructureType::A);
assert(a.a == 1);
assert(a.b == 2);
}
{
A a{.a = 1};
assert(reinterpret_cast<Reference const*>(&a)->s == StructureType::A);
assert(a.a == 1);
assert(a.b == 23);
}
{
A a;
assert(reinterpret_cast<Reference const*>(&a)->s == StructureType::A);
assert(a.a == 42);
assert(a.b == 23);
}
// A a{ StructureType::B, 2, 3}; // compile time error
// A a{ {StructureType::B}, 2, 3}; // compile time error
// A a{ .sType = StructureType::B, .a = 2, .b = 3}; // compile time error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment