Dukales

high-density packaging

May 17th, 2013
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #!/usr/bin/env bash -vex
  2. WARN="-W -Wall -Wextra -Werror -Wsign-promo -Wconversion -Wsign-conversion"
  3. g++ -x c++ - -std=gnu++1y $WARN -Ofast -o a <<__EOF && ./a && echo -e "\e[1;32msucceeded\e[0m" || echo -e "\e[1;31mfailed\e[0m"
  4. #include <iostream>
  5. #include <iterator>
  6. #include <algorithm>
  7. #include <new>
  8. #include <array>
  9. #include <tuple>
  10.  
  11. #include <cstdlib>
  12. #include <cassert>
  13.  
  14. template< typename F >
  15. struct repacker
  16. {
  17.  
  18.     static_assert(std::is_pod< F >::value, "Underlying type is not a POD type.");
  19.  
  20.     using pointer = F *;
  21.  
  22.     explicit
  23.     repacker(pointer const & _storage)
  24.         : storage_(_storage)
  25.     {
  26.         assert((reinterpret_cast< std::uintptr_t >(storage_) % std::alignment_of< F >::value) == 0);
  27.     }
  28.  
  29.     template< typename... P >
  30.     constexpr
  31.     auto operator () (P &&... p) const
  32.     {
  33.                 constexpr auto const N = sizeof...(P);
  34.                 using A = F [N];
  35.                 static_assert((sizeof(A) == sizeof(F) * N), "Check an alignment of the underlying type and the packing of it.");
  36.                 std::ignore = new (storage_) A{static_cast< F >(p)...};
  37.                 return N;
  38.     }
  39.  
  40. private :
  41.  
  42.     pointer const & storage_;
  43.  
  44. };
  45.  
  46. int main()
  47. {
  48.     using F = double;
  49.     constexpr auto N = 6;
  50.     F * a = new F[N];
  51.     {
  52.         F x(1.0);
  53.         F const y(2.0);
  54.         repacker< F > r(a);
  55.         auto const M = r(x, y, 3.0, 4, 5.0f, 6.0L);
  56.         assert(M == N);
  57.     }
  58.     std::copy_n(a, N, std::ostream_iterator< F const & >(std::cout, " "));
  59.     std::cout << std::endl;
  60.     delete [] a;
  61.     return EXIT_SUCCESS;
  62. }
  63. __EOF
Advertisement
Add Comment
Please, Sign In to add comment