fork(1) download
  1. #include <array>
  2. #include <iostream>
  3. #include <cstddef>
  4. #include <cstdint>
  5.  
  6. // This template will be instantiated repeatedly with VItems list
  7. // populated with new items.
  8. template<typename TItem, TItem... VItems> class
  9. t_PackImpl
  10. {
  11. // This template will be selected for second and all other blocks.
  12. public: template<TItem... VInnerItems> using
  13. t_Pack = t_PackImpl
  14. <
  15. TItem
  16. // add all previous items
  17. , VItems...
  18. // add item holding amount of items in new block
  19. , TItem{static_cast<TItem>(sizeof...(VInnerItems))}
  20. // add new block items
  21. , VInnerItems...
  22. >;
  23.  
  24. // This method will be called on the last instantiated
  25. // template with VItems containing all the items.
  26. // Returns array containing all the items with extra 0 item at the end.
  27. public: static constexpr auto
  28. to_array(void) -> ::std::array<TItem, sizeof...(VItems) + ::std::size_t{1}>
  29. {
  30. return {VItems..., TItem{}};
  31. }
  32. };
  33.  
  34. // This template will be instantiated just once.
  35. // Starts t_PackImpl instantiation chain.
  36. template<typename TItem> class
  37. t_BeginPack
  38. {
  39. // This template will be selected for first block.
  40. public: template<TItem... VInnerItems> using
  41. t_Pack = t_PackImpl
  42. <
  43. TItem
  44. // add item holding amount of items in new block
  45. , TItem{static_cast<TItem>(sizeof...(VInnerItems))}
  46. // add new block items
  47. , VInnerItems...
  48. >;
  49. };
  50.  
  51. int main()
  52. {
  53. {
  54. constexpr auto items
  55. {
  56. t_BeginPack<::std::uint8_t>::t_Pack<42>::to_array()
  57. };
  58. for(auto const & item: items)
  59. {
  60. ::std::cout << static_cast<::std::uint32_t>(item) << ::std::endl;
  61. }
  62. }
  63. ::std::cout << "----------------" << ::std::endl;
  64. {
  65. constexpr auto items
  66. {
  67. t_BeginPack<::std::uint8_t>::t_Pack<0, 1, 2>::to_array()
  68. };
  69. for(auto const & item: items)
  70. {
  71. ::std::cout << static_cast<::std::uint32_t>(item) << ::std::endl;
  72. }
  73. }
  74. ::std::cout << "----------------" << ::std::endl;
  75. {
  76. constexpr auto items
  77. {
  78. t_BeginPack<::std::uint8_t>::
  79. t_Pack<0, 1, 2>::
  80. t_Pack<0, 1>::
  81. t_Pack<0, 1, 2, 3, 4, 5>::to_array()
  82. };
  83. for(auto const & item: items)
  84. {
  85. ::std::cout << static_cast<::std::uint32_t>(item) << ::std::endl;
  86. }
  87. }
  88. return(0);
  89. }
  90.  
Success #stdin #stdout 0s 16056KB
stdin
Standard input is empty
stdout
1
42
0
----------------
3
0
1
2
0
----------------
3
0
1
2
2
0
1
6
0
1
2
3
4
5
0