5

In this simplified code :

template <int... vars>
struct Compile_Time_Array_Indexes
{
    static std::array < int, sizeof...(vars)> indexes;//automatically fill it base on sizeof...(vars)
};
template <int ... vars>
struct Compile_Time_Array :public Compile_Time_Array_Indexes<vars...>
{
};

I want to automatically fill indexes base on the vars... size .

Example :

Compile_Time_Array <1,3,5,2> arr1;//indexes --> [0,1,2,3]
Compile_Time_Array <8,5> arr2;   // indexes --> [0,1]

Any idea ?

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
uchar
  • 2,552
  • 4
  • 29
  • 50
  • 3
    C++14 brought [`std::integer_sequence`](http://en.cppreference.com/w/cpp/utility/integer_sequence) (though if these are indices, you might consider using `std::size_t`, which has a nice premade `std::index_sequence` for it). – chris Jun 10 '14 at 18:00
  • 2
    something like [this Q&A](http://stackoverflow.com/a/19023500/819272)? (also works without `constexpr` IIRC) – TemplateRex Jun 10 '14 at 18:26

1 Answers1

7

The following definition apparently works with GCC-4.9 and Clang-3.5:

template <typename Type, Type ...Indices>
auto make_index_array(std::integer_sequence<Type, Indices...>)
    -> std::array<Type, sizeof...(Indices)>
{
    return std::array<Type, sizeof...(Indices)>{Indices...};
}

template <int... vars>
std::array<int, sizeof...(vars)> 
Compile_Time_Array_Indexes<vars...>::indexes
    = make_index_array<int>(std::make_integer_sequence<int, sizeof...(vars)>{});
nosid
  • 48,932
  • 13
  • 112
  • 139
  • 2
    This doesn't fill the array with indices, though. Rather, it fills array with the same numbers as in the parameter pack. – chris Jun 10 '14 at 18:03
  • @chris: You are right. I didn't see that in the OP's question. I have fixed the answer. – nosid Jun 10 '14 at 18:13
  • 1
    @OP, Just so you know, there are many implementations of such an integer sequence for C++11 such that you could grab one and use it with this code. – chris Jun 10 '14 at 18:17
  • @nosid I'm trying to compile it in vs 2013 I add an implementation of make_integer_sequence but this line give me an error `Compile_Time_Array_Indexes::indexes` : `missing ';' before '<'` – uchar Jun 10 '14 at 18:33
  • 1
    @xyz Here, I used the standard "indecies trick" to make this work in C++11: http://coliru.stacked-crooked.com/a/0113a31abe51b68f. It _ought_ to work in VS2013. – Mooing Duck Jun 10 '14 at 19:01
  • @Casey tnx . you should make it an answer . – uchar Jun 10 '14 at 19:05
  • @MooingDuck visual studio 2013 does not support constexpr :( – uchar Jun 10 '14 at 19:12