function(pointer) as template argument, explicit template instantiation

data pulverizer data.pulverizer at gmail.com
Fri Dec 31 09:01:10 UTC 2021


On Friday, 31 December 2021 at 00:57:26 UTC, kdevel wrote:
> ```dptr.d
> class R {
> }
>
> void foo (R r)
> {
> }
>
> alias fn = void function (R);
>
> void lyr (fn F) (R r)
> {
> }
>
> immutable fn foo_ptr = &foo; // line 14
> pragma (msg, typeof (foo_ptr));
>
> auto ptr = lyr!(foo_ptr);    // line 17
> ```
> dmd reports:
>
> ```
> immutable(void function(R))
> dptr.d(14): Error: expression `& foo` is not a valid template 
> value argument
> ```
>
> If I comment out line 17 the code compiles. I want to put the 
> explicitly instantiated function template into an immutable AA. 
> How can that be phrased such that dmd compiles it?

Pointers are runtime entities and are not suitable template 
parameters (compile time).

So assuming that you are trying to either pass a function 
constant of a specific type signature as a template argument, or 
a function pointer as an argument with either a template 
specialisation or constraint:


```
class R {}
void foo(R r){}
alias fn = void function(R);

//function compile time constant
void lyr(fn fp_type)(R r){}

//As template constraint
void con(T)(T fun, R r)
if(is(T == fn))
{
   fun(r);
}

/*
   //As template specialisation
   void con(T: fn)(T fun, R r)
   {
     fun(r);
   }
*/

//Function constant
enum fn foo_ptr = (R r){};
pragma(msg, typeof(foo_ptr));

//Declared at compile time but only executable at runtime
auto ptr = &lyr!(foo_ptr);

void main()
{
   //auto ptr = &lyr!(foo_ptr);//could declare this here
   ptr(new R());
   fn new_ptr = &foo;
   con(new_ptr, new R());
}

```


More information about the Digitalmars-d-learn mailing list