AlignedData.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #ifndef CORE_ALIGNED_DATA_HPP
  2. #define CORE_ALIGNED_DATA_HPP
  3. #define CORE_ASSERT_ALIGNED_DATA(var, type) \
  4. static_assert(sizeof(var) == sizeof(type), "aligned data size missmatch"); \
  5. static_assert(decltype(var)::getSize() >= decltype(var)::getAlignment(), \
  6. "size >= alignment"); \
  7. static_assert(alignof(decltype(var)) == alignof(type), \
  8. "aligned data alignment missmatch");
  9. namespace Core {
  10. template<int SIZE, int ALIGNMENT>
  11. class alignas(ALIGNMENT) AlignedData final {
  12. static_assert(SIZE > 0, "size must be positive");
  13. char buffer[static_cast<unsigned int>(SIZE)] = {};
  14. public:
  15. template<typename T>
  16. constexpr T* as() {
  17. return reinterpret_cast<T*>(this);
  18. }
  19. template<typename T>
  20. constexpr const T* as() const {
  21. return reinterpret_cast<T*>(this);
  22. }
  23. static consteval int getSize() {
  24. return SIZE;
  25. }
  26. static consteval int getAlignment() {
  27. return ALIGNMENT;
  28. }
  29. };
  30. template<typename T>
  31. using AlignedType = AlignedData<sizeof(T), alignof(T)>;
  32. }
  33. #endif