Strange template problem

Tom S h3r3tic at remove.mat.uni.torun.pl
Sat Jul 8 13:36:43 PDT 2006


Kirk McDonald wrote:
> I'm having some trouble with a very odd template problem. Take the 
> following code:
> 
> [test.d]
> import std.stdio;
> import ftype; // Daniel Keep's ftype module
> 
> // A function with default arguments
> void foo(int i=20, char[] s="Monkey") {
>     writefln("foo: %s %s", i, s);
> }
> 
> // A function with the same arguments and no defaults
> void bar(int i, char[] s) {
>     writefln("bar: %s %s", i, s);
> }
> 
> // A function that takes a function pointer and the minimum
> // number of arguments the function can be called with, and
> // calls it.
> void Baz(fn_t, uint MIN_ARGS)(fn_t fn) {
>     static if (MIN_ARGS == 0)
>         fn();

MIN_ARGS is 0 for 'foo', because thats what the NumberOfArgs template 
returns, using the function *alias*. the *type* doesnt tell the compiler 
that it can be called with no args. thats just a func type that takes 
two args. thus the error.


>     else static if (MIN_ARGS == 1)
>         fn(10);
>     else static if (MIN_ARGS == 2)
>         fn(15, "Copper");
> }
> 
> // A template function that takes a function alias and the
> // minimum number of args it can be called with, and calls
> // Baz
> void Blah(alias Fn, uint MIN_ARGS = NumberOfArgs!(typeof(&Fn))) () {
>     alias typeof(&Fn) fn_t;
>     fn_t fn = &Fn;
>     Baz!(fn_t, MIN_ARGS)(fn);
> }
> 
> void main() {
>     Blah!(bar);    // Line 28
>     Blah!(foo, 0); // Line 29
> }
> 
> $ build test
> test.d(14): Error: expected 2 arguments, not 0
> 
> test.d(24): template instance test22.Baz!(void(*)(int i, char[] s),0u) 
> error instantiating
> test.d(29): template instance test22.Blah!(foo,0) error instantiating
> 
> Curiously, this works if I comment out line 28:
> 
> $ build test
> gcc test.o ftype.o -o test -m32 -lphobos -lpthread -lm
> $ ./test
> foo: 20 Monkey
> 
> It also works if I comment out line 29 instead:
> 
> $ build test
> gcc test.o ftype.o -o test -m32 -lphobos -lpthread -lm
> $ ./test
> bar: 15 Copper
> 
> But if both lines are there together, it fails.
> 


-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d mailing list