Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Based on @Xeo's <a href="https://stackoverflow.com/a/13315884/819272">excellent idea</a>, here is an approach that lets you fill an array of</p> <ul> <li><code>constexpr std::array&lt;T, N&gt; a = { fun(0), fun(1), ..., fun(N-1) };</code></li> <li>where <code>T</code> is any literal type (not just <code>int</code> or other valid non-type template parameter types), but also <code>double</code>, or <code>std::complex</code> (from C++14 onward)</li> <li>where <code>fun()</code> is any <code>constexpr</code> function</li> <li>which is supported by <code>std::make_integer_sequence</code> from C++14 onward, but easily implemented today with both g++ and Clang (see Live Example at the end of the answer)</li> <li>I use @JonathanWakely 's <a href="https://gitorious.org/redistd/integer_seq/raw/fdce85d18df4ea99240524c626d5452a0f7c3faf:integer_seq.h" rel="noreferrer">implementation at GitHub</a> (Boost License)</li> </ul> <p>Here is the code</p> <pre><code>template&lt;class Function, std::size_t... Indices&gt; constexpr auto make_array_helper(Function f, std::index_sequence&lt;Indices...&gt;) -&gt; std::array&lt;typename std::result_of&lt;Function(std::size_t)&gt;::type, sizeof...(Indices)&gt; { return {{ f(Indices)... }}; } template&lt;int N, class Function&gt; constexpr auto make_array(Function f) -&gt; std::array&lt;typename std::result_of&lt;Function(std::size_t)&gt;::type, N&gt; { return make_array_helper(f, std::make_index_sequence&lt;N&gt;{}); } constexpr double fun(double x) { return x * x; } int main() { constexpr auto N = 10; constexpr auto a = make_array&lt;N&gt;(fun); std::copy(std::begin(a), std::end(a), std::ostream_iterator&lt;double&gt;(std::cout, ", ")); } </code></pre> <p><a href="http://coliru.stacked-crooked.com/a/663dee82db2aef0a" rel="noreferrer"><strong>Live Example</strong></a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload