erased_storage.h 2.2 KB

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