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 ?

2
  • 3
    C++14 brought std::integer_sequence (though if these are indices, you might consider using std::size_t, which has a nice premade std::index_sequence for it). Commented Jun 10, 2014 at 18:00
  • 2
    something like this Q&A? (also works without constexpr IIRC) Commented Jun 10, 2014 at 18:26

1 Answer 1

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)>{});
Sign up to request clarification or add additional context in comments.

7 Comments

This doesn't fill the array with indices, though. Rather, it fills array with the same numbers as in the parameter pack.
@chris: You are right. I didn't see that in the OP's question. I have fixed the answer.
@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.
@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<vars...>::indexes : missing ';' before '<'
@xyz Here, I used the standard "indecies trick" to make this work in C++11: coliru.stacked-crooked.com/a/0113a31abe51b68f. It ought to work in VS2013.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.