Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // This simple variant gets the job done without
  2. // causing too much trouble with template depth:
  3. //
  4. // * Always allows an empty state I==0
  5. // * emplace() and get() support 1-based indexes only
  6. // * Basic exception guarantee
  7. // * Max 255 types
  8. //
  9. template<class... TN>
  10. class variant
  11. {
  12. std::array<char, max_sizeof<TN...>()> buf_;
  13. unsigned char i_ = 0;
  14.  
  15. template<std::size_t I>
  16. using type = typename std::tuple_element<
  17. I , std::tuple<TN...>>::type;
  18.  
  19. template<std::size_t I>
  20. using C = std::integral_constant<std::size_t, I>;
  21.  
  22. public:
  23. variant() = default;
  24.  
  25. ~variant()
  26. {
  27. if(n_)
  28. destroy(C<0>{});
  29. }
  30.  
  31. template<std::size_t I, class... Args>
  32. void
  33. emplace(Args&&... args)
  34. {
  35. if(n_ != 0)
  36. destroy(C<0>{});
  37. n_ = 0;
  38. new(buf_.data()) type<I>(
  39. std::forward<Args>(args)...);
  40. n_ = I;
  41. }
  42.  
  43. template<std::size_t I>
  44. type<I-1>&
  45. get()
  46. {
  47. BOOST_ASSERT(I == n_ - 1);
  48. return *reinterpret_cast<
  49. type<I>*>(buf_.data());
  50. }
  51.  
  52. template<std::size_t I>
  53. type<I-1>&
  54. get() const
  55. {
  56. BOOST_ASSERT(I == n_ - 1);
  57. return *reinterpret_cast<
  58. type<I> const*>(buf_.data());
  59. }
  60.  
  61. private:
  62. void
  63. destroy(C<sizeof...(TN)>)
  64. {
  65. return;
  66. }
  67.  
  68. template<std::size_t I>
  69. void
  70. destroy(C<I>)
  71. {
  72. if(I == n_ - 1)
  73. {
  74. type<I>.~type<I>();
  75. return;
  76. }
  77. destroy(C<I+1>{});
  78. }
  79. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement