www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is it possible to call a delegate at compile time?

reply Andrew Edwards <edwards.ac gmail.com> writes:
auto foo(Args...)(ref Args args)
{
     with (Module!"std.conv")
     with (Module!"std.stdio") {
         return () => {
             string[] s;
             foreach (i, arg; args) {
                 static if (is(Args[i] == string)) {
                     s ~= arg;
                 } else {
                     s ~= to!string(arg);
                 }
             }

             debug writeln(fmt());
             return cast(immutable)s;
         }();
     }
}

template Module(string name)
{
     mixin("import Module = " ~ name ~ ";");
}

void main()
{
     static immutable i = 7;
     static immutable s = "teen";

     static immutable res = foo(i, s)();
     writeln(res);
}

I desire to call foo() at compile...  As implemented it does not 
happen, but it's not immediately clear what I am missing. Or is 
this simply not possible as yet? What is the proper way to 
redesign this template so that it will execute at compile time?

Thanks,
Andrew
Jun 22
parent reply ketmar <ketmar ketmar.no-ip.org> writes:
Andrew Edwards wrote:

 I desire to call foo() at compile...  As implemented it does not happen, 
 but it's not immediately clear what I am missing. Or is this simply not 
 possible as yet? What is the proper way to redesign this template so that 
 it will execute at compile time?
there are two caveats. the first is `ref` in Args: that won't work for arguments in CTFE (it works for nested functions, though). and second, whith you can't fight right now: "Error: closures are not yet supported in CTFE". so no, even if you'll remove `ref`, it will not work. sorry.
Jun 22
parent Andrew Edwards <edwards.ac gmail.com> writes:
On Friday, 23 June 2017 at 04:58:07 UTC, ketmar wrote:
 Andrew Edwards wrote:

 so no, even if you'll remove `ref`, it will not work. sorry.
Okay, got it. Much appreciated.
Jun 22