Search code examples
c++templatestemplate-meta-programmingstdarray

Compute differences of pair elements in array of pairs compile time


In the code below, I aim to construct an array of N elements that contains the differences between two std::pair elements compile time. Is there a way to achieve this using templates, as it has to work for arbitrary size N?

#include <array>
#include <utility>

template<int N>
std::array<int, N> make_array(
        const std::array<std::pair<int, int>, N>& ranges)
{
    // Need to construct array compile time with difference between pair elements.
}

int main()
{
    std::array<int, 2> a = make_array<2>({{ {1,3}, {2,9} }}); // a = {2, 7}
    std::array<int, 1> b = make_array<1>({{ {5,6} }}); // b = {1}

    return 0;
}

Solution

  • You can simply do the loop:

    template <std::size_t N>
    constexpr std::array<int, N> make_array(
            const std::array<std::pair<int, int>, N>& ranges)
    {
        std::array<int, N> res{};
    
        for (std::size_t i = 0; i != N; ++i) {
            res[i] = ranges[i].second - ranges[i].first;
        }
        return res;
    }
    

    It might be constexpr since C++17.

    Demo