Strange error
Steven Schveighoffer
schveiguy at gmail.com
Sun Mar 21 12:20:31 UTC 2021
On 3/21/21 3:18 AM, Jack Applegame wrote:
> Could someone please explain what is wrong with this code?
>
> https://glot.io/snippets/fwxn2198kv
>
> ```d
> import std.stdio;
>
> struct Sample{
> void function() func1;
> void function() func2;
> }
>
> void noth(Sample smpl)() {
> smpl.func1(); // Error: expression __lambda1 is not a valid template
> value argument
> smpl.func2(); // Error: expression __lambda2 is not a valid template
> value argument
> }
>
> void main(){
> enum s = Sample(
> {writeln("Hello world1");},
> {writeln("Hello world2");}
> );
> s.func1();
> s.func2();
> noth!(s)();
> }
> ```
You have the wrong lines attributed with the error message. The error
message is in the assignment of s (line 15 and 16)
Essentially, you can't use lambda functions as compile-time values.
Valid template value parameters are [1]
"any type which can be statically initialized at compile time. Template
value arguments can be integer values, floating point values, nulls,
string values, array literals of template value arguments, associative
array literals of template value arguments, or struct literals of
template value arguments."
Now, one might argue that it's possible to statically initialize
function pointers at compile time (i.e. you can do this as a static
initialized function pointer at module scope), so possibly this is
something that can be fixed. There might already be a bug report on it,
or you can file one. It might end up with the spec being clarified to
explicitly cover this case.
-Steve
[1] https://dlang.org/spec/template.html#template_value_parameter
More information about the Digitalmars-d-learn
mailing list