<div class="gmail_quote">2010/8/23 Stanislav Blinov <span dir="ltr">&lt;<a href="mailto:blinov@loniir.ru">blinov@loniir.ru</a>&gt;</span><br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<div><div></div>I have a struct template (let&#39;s call it S) that wraps an array of N elements. N is set at compile time via template parameter. S uses static array as storage (T[N]). I need a set of constants of type S which I&#39;d like to be evaluatable at compile time. I can create these constants with the following constructs:<br>
</div>
<br>
static immutable S C1 = { /* initialization of struct fields here */ };<br>
static immutable S C2 = { /* initialization of struct fields here */ };<br>
<br>
Hence, I need some way to initialize a field which is T[N].<br>
<br>
Later, I could use those constants like this:<br>
<br>
class Foo<br>
{<br>
    S s1_ = S.C1;<br>
    S s2_ = S.C2;<br>
}<br>
<br>
I can write a set of initializers for some values of N, but I&#39;d like them to be generic so that I could apply them for arbitrary value of N.<br>
E.g. one can do things like T[3] a = [ 1, 2, 3 ], but I&#39;d like to be able to do T[N] = SomeInitializerForArrayOfNElements;<br>
<br>
What I&#39;m trying to achieve is:<br>
<br>
1. Initialize T[N] elements to a specific value.<br>
2. Initialize every element of T[N] to some value deduced at compile time using it&#39;s index.<br>
<br>
I came up with the templates in my initial post. They seem to work, but I doubt those are legal solutions.<br>
</blockquote></div><br>If they work, then they are legal :)<br><br>If I understand correctly what you want, you can achieve it with compile-time-evaluable functions:<br><br>module main;<br>import std.stdio;<br><br>/**<br>
return a T[N] with all elements equal to t.<br>*/<br>T[N] initializeWith(T, size_t N)(T t) if (N&gt;0)<br>{<br>    T[N] result;<br>    foreach(i, _; result)<br>    {<br>        result[i] = t;<br>    }<br>    return result;<br>
}<br><br>/**<br>Returns a T[N] with all elements equal to foo(index)<br>*/<br>T[N] initializeWith(alias fun, T, size_t N)() if (N&gt;0)<br>{<br>    T[N] result;<br>    foreach(i, _; result)<br>    {<br>        result[i] = fun(i);<br>
    }<br>    return result;<br>}<br><br>int foo(int i) { return i*i;}<br><br>struct S<br>{<br>    static immutable int[10] arr = initializeWith!(foo, int, 10);<br>}<br><br>void main()<br>{<br>    auto a = initializeWith!(int,10)(8);<br>
<br>    writeln(a);<br>    a = initializeWith!(foo,int,10);<br>    writeln(a);<br>    S s;<br>    writeln(s.arr);<br>}<br><br>Does that work for you? <br><br>Philippe<br><br>