www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Function template as template parameter

reply Andrey Zherikov <andrey.zherikov gmail.com> writes:
I have this (very simplified) code:
```d
void foo(alias callback)()
{
     callback!5;
}

static void print(int i)() { writeln(i); }
foo!print;
```

Is there a way to merge two last lines into one of a form like 
`foo!(...something...)`?

Note that callback parameter must be compile-time parameter as it 
represents a member of a type during introspection done by `foo`.
Dec 11 2022
parent reply Salih Dincer <salihdb hotmail.com> writes:
On Sunday, 11 December 2022 at 09:43:34 UTC, Andrey Zherikov 
wrote:
 Note that callback parameter must be compile-time parameter as 
 it represents a member of a type during introspection done by 
 `foo`.
I can't quite understand the question, this already works: ```d void foo(alias callback)() { import std.stdio : writefln; callback.writefln!"%s"; } void main() { auto i = [ 1, 2, 3 ]; auto s = ["foo", "bar", "zoo"]; foo!i; foo!s; foo!"hello, world!"; enum a = 11, b = 22; foo!(a + b); } /* [1, 2, 3] ["foo", "bar", "zoo"] hello, world! 33 */ ```
Dec 11 2022
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 12/11/22 05:54, Salih Dincer wrote:
 On Sunday, 11 December 2022 at 09:43:34 UTC, Andrey Zherikov wrote:
 Note that callback parameter must be compile-time parameter as it
 represents a member of a type during introspection done by `foo`.
I can't quite understand the question, this already works:
I think the OP is trying to create an anonymous template. I don't think it's possible. The following works because the template has the name 'print': // Named template: static void print(int i)() { import std; writeln(i); } void main() { foo!print; } The following does not work when one attempts to use the template anonymously. Just trying to pass a template just like a lambda: foo!((int i)() { import std; writeln(i); }); Note how '(int i)()' is hoping to define a template. Ali
Dec 11 2022
parent Andrey Zherikov <andrey.zherikov gmail.com> writes:
On Sunday, 11 December 2022 at 16:24:30 UTC, Ali Çehreli wrote:
 On 12/11/22 05:54, Salih Dincer wrote:
 On Sunday, 11 December 2022 at 09:43:34 UTC, Andrey Zherikov
wrote:
 Note that callback parameter must be compile-time parameter
as it
 represents a member of a type during introspection done by
`foo`.
 I can't quite understand the question, this already works:
I think the OP is trying to create an anonymous template.
Yes
 The following does not work when one attempts to use the 
 template anonymously. Just trying to pass a template just like 
 a lambda
Thanks for confirming this.
Dec 11 2022