How to repeat a function call?

w0rp devw0rp at gmail.com
Wed Apr 2 12:33:27 PDT 2014


tuples are definitely a compile-time job. You could do something 
like this to build an N tuple by calling a function N many times.

---
import std.typecons;

int foo() {
     return 3;
}

auto initTuple(size_t N, alias func)() {
     string magic() {
         string result = "return tuple(";

         foreach(i; 0..N) {
             result ~= "func(),";
         }

         result ~= ");";

         return result;
     }

     mixin(magic());
}

void main(string[] argv) {
     enum Tuple!(int, int, int) tup = initTuple!(3, foo);
}

---

This just builds the tuple by building up a mixin string which 
calls the function so many times, with no guarantees about the 
order of arguments. If you have side-effects in your function 
though, you probably want to move it runtime anyway and use a 
range with the 'repeat' function, etc.


More information about the Digitalmars-d-learn mailing list