mercredi 18 novembre 2020

(C++11) Variadic template sequence printing

I was given a template meta-programming challenge of using only C++11 standard to print out a series of integers in powers of 2 which I have successfully done:

#include <iostream>

template <size_t... Ns>
struct index_sequence
{
    static void print()
    {
        const size_t numbers[] = {Ns...};
        for (const auto& number : numbers)
        {
            std::cout << number << ", ";
        }
        std::cout << std::endl;
    }
};

//#include <cmath>

template <size_t Counter, size_t... Rest>
struct make_sequence_impl
{
    using type = typename make_sequence_impl<
        Counter - 1,
        static_cast<size_t>(1) << Counter, Rest...>::type;
};

template <size_t... Rest>
struct make_sequence_impl<0, Rest...>
{
    using type = index_sequence<static_cast<size_t>(1) << 0, Rest...>;
};

template <size_t T>
using make_sequence = typename make_sequence_impl<T>::type;

int main()
{
    make_sequence<N>::print();
}

Assuming N is 5, it would print 1, 2, 4, 8, 16.

However, I was subsequently challenged to do the same thing, except that this time I have to print them in reverse order (i.e. 16, 8, 4, 2, 1 for N = 5). I am totally stumped but I am very sure it involved only a slight change to the code which I can't figure out how.

Any help would be appreciated. Got into template meta-programming a few days ago.

Aucun commentaire:

Enregistrer un commentaire