Advertisement
Guest User

Untitled

a guest
May 28th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #pragma once
  2. #include <type_traits>
  3. #include <utility> // for std::forward
  4. #include "utils.hh"
  5. #include "constraints.hh"
  6. #include "const-helper.macro.hh"
  7.  
  8. namespace meta
  9. {
  10. template <class NIL, class ...MEMBERS>
  11. struct aligned_union : non_transferable
  12. {
  13. using self = aligned_union;
  14.  
  15. template <class T>
  16. static constexpr auto nil_requirement =
  17. std::is_nothrow_constructible<T>::value &&
  18. std::is_nothrow_destructible <T>::value;
  19.  
  20. using nil = std::decay_t<NIL>;
  21. static_assert(nil_requirement<nil>, "NIL does not meet the nil-requirement");
  22.  
  23. static constexpr auto alignment_value()
  24. {
  25. return utils::alignment_of<nil, std::decay_t<MEMBERS>...>;
  26. }
  27.  
  28. static constexpr auto size()
  29. {
  30. return utils::max(sizeof(nil), sizeof(std::decay_t<MEMBERS>)...);
  31. }
  32.  
  33. template <class T, class = utils::disable_if_base_of<self, T>>
  34. aligned_union(T&& x) { construct<T>(std::forward<T>(x)); }
  35. aligned_union() : aligned_union{nil{}} {}
  36.  
  37. template <class T, class ...TS>
  38. void construct(TS&&... xs)
  39. {
  40. using type = std::decay_t<T>;
  41. try {
  42. new (data) type(std::forward<TS>(xs)...);
  43. }
  44. catch (...) {
  45. new (data) nil;
  46. throw;
  47. }
  48. }
  49.  
  50. template <class T>
  51. void destruct() { data.~T(); }
  52.  
  53. CONST_HELPER(
  54. template <class T>
  55. auto& as() CONST noexcept
  56. {
  57. using type = utils::const_if<decltype(this), std::decay_t<T>>;
  58. return *reinterpret_cast<type *>(data);
  59. }
  60. );
  61.  
  62. private:
  63. alignas(alignment_value()) char data[size()];
  64. };
  65. }
  66.  
  67. #include "const-helper.undef.hh"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement