fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. // Эта штука чтобы получить количество элементов в __VA_ARGS__ как compile-time константу
  5. // используется в sizeof выражении, поэтому не требуется реализация методов
  6. template<class T, std::size_t Count>
  7. struct comma_counter
  8. {
  9. static comma_counter<T, Count> make();
  10.  
  11. comma_counter<T, Count + 1> operator,(T);
  12.  
  13. typedef char ch_array[Count];
  14. ch_array& to_ch_array();
  15. };
  16.  
  17. #define COUNT_ARGS(type, ...) sizeof((comma_counter<type, 0>::make(),__VA_ARGS__).to_ch_array())
  18.  
  19. // Здесь хранятся элементы
  20. template<class T, std::size_t Count>
  21. struct temporary_storage
  22. {
  23. T data[Count];
  24.  
  25. static temporary_storage<T, Count> make() { return temporary_storage(); }
  26.  
  27. // Это заполняет хранилище
  28. template<std::size_t Pos>
  29. struct comma_filler
  30. {
  31. temporary_storage& st;
  32.  
  33. comma_filler(temporary_storage& st) : st(st) {}
  34.  
  35. comma_filler<Pos + 1> operator,(T t)
  36. {
  37. st.data[Pos] = t;
  38. return comma_filler<Pos + 1>(st);
  39. }
  40.  
  41. // Выдаёт результирующий контейнер
  42. template<class Container>
  43. Container to_container() const
  44. {
  45. return Container(st.data, st.data + Pos);
  46. }
  47. };
  48.  
  49. comma_filler<0> fill() { return comma_filler<0>(*this); }
  50. };
  51.  
  52. // Всё воедино
  53.  
  54. #define CREATE_CONTAINER(type, container, ...) \
  55.   (temporary_storage<type, \
  56.   sizeof((comma_counter<type, 0>::make(),__VA_ARGS__).to_ch_array())\
  57.   >::make().fill(), __VA_ARGS__).to_container<container>()
  58.  
  59. int main()
  60. {
  61. std::cout << COUNT_ARGS(int, 11, 22, 33) << '\n';
  62.  
  63. std::vector<int> v = CREATE_CONTAINER(int, std::vector<int>, 55, 66, 77, 88);
  64.  
  65. for (std::vector<int>::iterator i = v.begin(), e = v.end(); i != e; ++i)
  66. std::cout << *i << '\n';
  67. }
  68.  
  69.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
3
55
66
77
88