2014-06-10 29 views
4

在這種簡化代碼:如何根據可變參數模板的大小自動填充std :: array?

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...> 
{ 
}; 

我想自動填補vars...大小indexes基地。

例子:

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

任何想法?

+3

C++ 14帶來['的std :: integer_sequence'](http://en.cppreference.com/w/ cpp/utility/integer_sequence)(儘管如果這些是索引,你可能會考慮使用'std :: size_t',它有一個很好的預製'std :: index_sequence')。 – chris

+2

像[本問答](http://stackoverflow.com/a/19023500/819272)? (也可以在沒有'constexpr' IIRC的情況下運行) – TemplateRex

回答

7

下面的定義顯然與GCC-4.9和鏘-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)>{}); 
+2

儘管如此,它並沒有用索引填充數組。相反,它使用與參數包中相同的數字填充數組。 – chris

+0

@chris:你說得對。我在OP的問題中沒有看到這一點。我已經解決了答案。 – nosid

+1

@OP,大家知道,C++ 11有這樣一個整數序列的許多實現,這樣你就可以抓住一個並用這個代碼來使用它。 – chris

相關問題