AlignedData.hpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #ifndef CORE_ALIGNED_DATA_HPP
  2. #define CORE_ALIGNED_DATA_HPP
  3. #define alignmentof(type) __alignof__(type)
  4. #define ASSERT_ALIGNED_DATA(var, type) \
  5. static_assert(sizeof(var) == sizeof(type), "aligned data size missmatch"); \
  6. static_assert(var.getSize() >= var.getAlignment(), "size >= alignment"); \
  7. static_assert(alignmentof(var) == alignmentof(type), \
  8. "aligned data alignment missmatch");
  9. namespace Core {
  10. template<int SIZE, int ALIGNMENT>
  11. class alignas(ALIGNMENT) AlignedData {
  12. static_assert(SIZE > 0, "size must be positive");
  13. char buffer[static_cast<unsigned int>(SIZE)] = {};
  14. public:
  15. template<typename T>
  16. T* as() {
  17. return reinterpret_cast<T*>(this);
  18. }
  19. template<typename T>
  20. 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), alignmentof(T)>;
  32. }
  33. #endif