mardi 1 décembre 2015

Mutiplying each element of an std::array at compile time

I would like to convert an std::array to another std::array, mulitplying each of its elements by a specific number.

What I have right now obviously doesn't work:

#include <array>
#include <iostream>
#include <utility>

template <class T, size_t... Is, size_t N>
constexpr std::array<T, N> multiply(std::array<T, N> const &src,
                                  std::index_sequence<Is...>) {
    return std::array<T, N>{{src[Is]...}}; // How can I multiply each of src's elements?
}

int main(int argc, char *argv[]) {
    constexpr std::array<int, 3> arr = {1, 2, 3};
    constexpr auto t = multiply(arr, std::make_index_sequence<3>{});
    for (auto &el : t) std::cout << el << std::endl;
    return 0;
}

My question is: how can I iterate over each element at compile time or how can I apply the same function (in my case: multiply by 2) at compile time?

Aucun commentaire:

Enregistrer un commentaire