Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. template<unsigned int N>
  2. class A { ... }
  3.  
  4. for(unsigned int i = 0; i < 10; ++i) {
  5. A<i>().doStuff();
  6. }
  7.  
  8. A<1> first;
  9. A<2> second;
  10. A<42> third;
  11. A<1034> fourth;
  12.  
  13. void doAppropriateStuff(int value) {
  14. if (value < 1) {
  15. first.doStuff();
  16. } else if (value < 2) {
  17. second.doStuff();
  18. } else if (value < 42) {
  19. third.doStuff();
  20. } else if (value < 1034) {
  21. fourth.doStuff();
  22. } else {
  23. ...
  24. }
  25. }
  26.  
  27. #include <iostream>
  28.  
  29. template<unsigned int N>
  30. struct A {
  31. void dostuff() const { std::cout << N << " "; }
  32. };
  33.  
  34. template < int N > void run();
  35.  
  36. template <> void run<-1>() {}
  37. template < int N > void run() {
  38. run<N-1>();
  39. A<N>{}.dostuff();
  40. }
  41.  
  42. int main() {
  43. run<10>();
  44. }
  45.  
  46. #include <iostream>
  47. #include <tuple>
  48.  
  49. template<unsigned int N>
  50. struct A {
  51. unsigned int getN() const { return N; }
  52. void dostuff() const { std::cout << N << " "; }
  53. };
  54.  
  55. auto globals = std::make_tuple( A<3>{}, A<7>{}, A<10>{}, A<200>{} );
  56.  
  57. template <int idx> void run( int v );
  58. template <> void run<std::tuple_size<decltype(globals)>::value>( int ) {}
  59. template <int idx = 0> void run( int v ) {
  60. auto & a = std::get<idx>(globals);
  61. if ( v < a.getN() ) {
  62. a.dostuff();
  63. } else {
  64. run<idx+1>(v);
  65. }
  66. }
  67.  
  68. int main() {
  69. for( int i = 0; i<20; ++i)
  70. run( i );
  71. }
  72.  
  73. template< std::size_t... Ns >
  74. struct indices {
  75. typedef indices< Ns..., sizeof...( Ns ) > next;
  76. };
  77.  
  78. template< std::size_t N >
  79. struct make_indices {
  80. typedef typename make_indices< N - 1 >::type::next type;
  81. };
  82.  
  83. template<>
  84. struct make_indices< 0 > {
  85. typedef indices<> type;
  86. };
  87.  
  88. #include <initializer_list>
  89.  
  90. template<size_t... Is>
  91. void foo(indices<Is...>)
  92. {
  93. auto list = { (A<Is>().doStuff(), 0)... };
  94. }
  95.  
  96. foo(make_indices<10>::type());
  97.  
  98. template <unsigned int N> struct ADoer
  99. {
  100. static void go() { A<N>().doStuff(); ADoer<N - 1>::go(); }
  101. };
  102.  
  103. template <> struct ADoer<0>
  104. {
  105. static void go() { }
  106. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement