Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++14 compile time std::array with variadic templates

I'd like to build a compile time lookup table using c++14 variadic templates. At the moment I'm there:

static const unsigned kCount = 5;

template<unsigned Index>
constexpr auto getRow(void)
{
    return std::array<unsigned, 2> { Index, Index * Index };
}

template<unsigned... Indices>
constexpr auto generateTable(std::index_sequence<Indices...>)
{
    return std::array<std::array<unsigned, 2>, sizeof...(Indices)>
    {
        // This is were I'm stuck. How to build a std::array using Indices as template parameter in getRow()?
    };
}

constexpr auto generate(void)
{
    return generateTable(std::make_index_sequence<kCount>{});
}

I want the table to be in a std::array. Each row consists of a std::array with 2 columns. I'm stuck in generateTable() where I need to somehow pass my Indices to getRow() as a template parameter.

Is this achievable using std::integer_sequence and template parameter pack expansion or do I need to implement the recursion on my own?

(getRow() is simplified - the value types are actually coming from templated types. Index * Index is just a placeholder. I need to know the way how to call getRow() using parameter pack expansion.)

like image 411
Wum Avatar asked Aug 30 '26 04:08

Wum


1 Answers

Looks like you're almost there. Just rely on parameter-pack expansion:

return std::array<std::array<unsigned, 2>, sizeof...(Indices)>
{
   getRow<Indices>()...
};

where the getRow<Indices>()... line will expand to:

getRow<0>(), getRow<1>(), ..... , getRow<sizeof...(Indices)-1>()
like image 153
KyleKnoepfel Avatar answered Aug 31 '26 18:08

KyleKnoepfel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!