Created
October 21, 2019 20:00
-
-
Save ekpyron/6d79fa7372a9178bc8ec0debadce5aae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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