c++ Index sequence…
After struggling a bit, I finally got it (I think)…Well at least its something that I understand and can work with.. Here is what I have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
constexpr int f(size_t a) { if( a == 0) { return 0; }else { return a += f(a-1); } } template< size_t N> struct Test { Test(){ std::cout << (int)N << "\n"; } static const int val=N; }; template< size_t N> class MyStorage { public: MyStorage(){ std::cout << "Construct" << "\n"; } template<int i> auto getTest() { return std::get<i>(ts_); } private: template<size_t... nr> using TsImpl = std::tuple< Test< f(nr)>...>; template< size_t... ts> static TsImpl<ts...> make_index_ts(std::index_sequence<ts...>) { return TsImpl<(ts)...>{}; } template<size_t n> static auto make_ts() { return make_index_ts(std::make_index_sequence<n>{}); } using Ts = decltype(make_ts<N>()); Ts ts_; }; int main() { MyStorage<8> testStorage; std::cout << "Value of index 0=" <<testStorage.getTest<0>().val << '\n' << "Value of index 1=" <<testStorage.getTest<1>().val << '\n' << "Value of index 2=" <<testStorage.getTest<2>().val << '\n' << "Value of index 3=" <<testStorage.getTest<3>().val << '\n' << "Value of index 4=" <<testStorage.getTest<4>().val << '\n' << "Value of index 5=" <<testStorage.getTest<5>().val << '\n' << "Value of index 6=" <<testStorage.getTest<6>().val << '\n' << "Value of index 7=" <<testStorage.getTest<7>().val << '\n' << '\n'; //MyStorage<4,Fisk> m; return 0; } |
Ok so what does it do…
output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
build ./IndexSeq 28 21 15 10 6 3 1 0 Construct Value of index 0=0 Value of index 1=1 Value of index 2=3 Value of index 3=6 Value of index 4=10 Value of index 5=15 Value of index 6=21 Value of index 7=28 |
It creates 8 Test objects at compile time and sets there value according to what index they have and the function f..Not much use, but quite useful in other cases.