Inferring function argument types from other argument types

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Mon Nov 12 04:42:12 PST 2012


Suppose that I've got a struct which internally defines a number of types:

     struct Foo(_T1, _T2)
     {
         alias _T1 T1;
         alias _T2 T2;
         T1 a;
         T2 b;
     }

... and now I want to define a function which takes as input an instance of one 
of these structs, and a variable of type T1.

I tried the following:

     T func(FooT, T = FooT.T1)(FooT foo, T x)
     {
         return x * foo.a;
     }

but found that the type of whatever I was passing would override the default: 
e.g. if I called func(fooInstance, 1) then the second argument would be 
interpreted as an int even though Foo.T1 is size_t.

I also tried,

     T func(FooT, T : FooT.T1)(FooT foo, T x)
     {
         return x * foo.a;
     }

but this generates a different error: "no property 'T1' for type 'FooT'".  I 
tried replacing FooT with alias FooT to no avail.

Obviously I could get round the problems of the first example with something 
based around CommonType etc. but I'm just wondering if it's possible to make an 
argument dependent on another template parameter in the way I'm looking for here.


More information about the Digitalmars-d-learn mailing list