Make constexpr array of function values I have a function f(i, j) that accepts two std::size_t arguments and I want to make a constexpr std:array out of its values on a 2d grid, (i = 0, ..., rows-1; j = 0, ..., cols-1) in, say, column-major order.

The code:

#include &lt;array&gt;
#include &lt;tuple&gt;
#include &lt;type_traits&gt;

template&lt;std::size_t rows, std::size_t cols&gt;
constexpr auto make_2d_index_table()
{
    std::array&lt;std::array&lt;std::size_t, 2&gt;, rows * cols&gt; table{};
    for (std::size_t i = 0; i &lt; table.size(); ++i)
        table[i] = {i % rows, i / rows};

    return table;
}

template&lt;std::size_t rows, std::size_t cols, class Func&gt;
constexpr std::array&lt;std::invoke_result_t&lt;Func, std::size_t, std::size_t&gt;, rows * cols&gt; 
    make_array_of_2d_func_values(Func&amp;&amp; func)
{
    return apply([&amp;func](auto... row_col)
    {
        return std::array&lt;std::invoke_result_t&lt;Func, std::size_t, std::size_t&gt;, rows * cols&gt;
            {std::apply(std::forward&lt;Func&gt;(func), row_col)...};
    }, make_2d_index_table&lt;rows, cols&gt;());
}


Usage:

constexpr auto arr = make_array_of_2d_func_values&lt;5, 3&gt;(
    [](auto i, auto j) { return i + 2 * j; });


The object of the type returned by a function may not be default constructible. So I can't just create an array&lt;invoke_result_t&lt;...&gt;, rows * cols&gt; arr{} of default constructed objects and then initialize it in the for loop like in make_index_table().

Is this a good solution?
One simple improvement: the return type of make_array_of_2d_func_values() can be auto, to save writing std::array&lt;std::invoke_result_t&lt;Func, std::size_t, std::size_t&gt;, rows * cols&gt; twice.

I think you may be able to specialize std::tuple_size and std::get for the index table so that it doesn't require any storage even when invoked with non-constexpr arguments; I'm still experimenting but expect an update to this answer!