C ++ 14:如何使用可变参数模板创建值1-100数组

Tro*_*yvs 2 c++ arrays templates list-comprehension variadic

我希望得到一组值int buf[]={1...100}。我希望可以使用可变参数模板在编译时构造此数组。这是像Python /哈斯克尔等的列表理解

但是c ++ 11/14模板可以做到吗,怎么办?谢谢

Pot*_*ter 5

C ++ 14允许在编译时进行循环。

constexpr auto make_upto_100() {
    std::array< int, 100 > ret = {};
    for ( int i = 0; i != 100; ++ i ) ret[i] = i + 1;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

C ++ 11允许像一个工具make_index_sequence,这可能是更喜欢你的想法。(C ++ 14也有std::[make_]index_sequence。)

template< std::size_t ... i >
struct index_sequence
    { typedef index_sequence< i ..., sizeof ... (i) > next; };

template< std::size_t last >
struct index_seq_maker
    { typedef typename index_seq_maker< last - 1 >::type::next type; };

template<>
struct index_seq_maker< 0 >
    { typedef index_sequence<> type; };

template< std::size_t n >
using make_index_sequence = typename index_seq_maker< n >::type;

template< int ... i >
constexpr
std::array< int, 100 >
make_upto_100( index_sequence< i ... > )
    { return {{ i + 1 ... }}; }

constexpr
std::array< int, 100 > upto_100() = make_upto_100( make_index_sequence< 100 >{} );
Run Code Online (Sandbox Code Playgroud)