erased_storage.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #pragma once
  2. #include <concepts>
  3. #include <memory>
  4. namespace NYT {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. constexpr size_t ErasedStorageMaxByteSize = 32;
  7. ////////////////////////////////////////////////////////////////////////////////
  8. class TErasedStorage;
  9. ////////////////////////////////////////////////////////////////////////////////
  10. template <class T>
  11. concept CTriviallyErasable =
  12. std::default_initializable<T> &&
  13. std::is_trivially_destructible_v<T> &&
  14. std::is_trivially_copyable_v<T> &&
  15. (sizeof(T) <= ErasedStorageMaxByteSize) &&
  16. (alignof(T) <= ErasedStorageMaxByteSize) &&
  17. !std::is_reference_v<T> &&
  18. !std::same_as<T, TErasedStorage>;
  19. ////////////////////////////////////////////////////////////////////////////////
  20. // This class does not call dtor of erased object
  21. // thus we require trivial destructability.
  22. class TErasedStorage
  23. {
  24. public:
  25. template <CTriviallyErasable TDecayedConcrete>
  26. explicit TErasedStorage(TDecayedConcrete concrete) noexcept;
  27. TErasedStorage(const TErasedStorage& other) = default;
  28. TErasedStorage& operator=(const TErasedStorage& other) = default;
  29. template <CTriviallyErasable TDecayedConcrete>
  30. TDecayedConcrete& AsConcrete() & noexcept;
  31. template <CTriviallyErasable TDecayedConcrete>
  32. const TDecayedConcrete& AsConcrete() const & noexcept;
  33. template <CTriviallyErasable TDecayedConcrete>
  34. TDecayedConcrete&& AsConcrete() && noexcept;
  35. private:
  36. // NB(arkady-e1ppa): aligned_storage is deprecated.
  37. alignas(ErasedStorageMaxByteSize) std::byte Bytes_[ErasedStorageMaxByteSize];
  38. };
  39. ////////////////////////////////////////////////////////////////////////////////
  40. } // namespace NYT
  41. #define ERASED_STORAGE_INL_H_
  42. #include "erased_storage-inl.h"
  43. #undef ERASED_STORAGE_INL_H_