Function template parameter inference from class template

Justin Johansson procode at adam-dott-com.au
Wed Sep 23 15:17:09 PDT 2009


Jarrett Billingsley Wrote:

> > If you have a function template of one type parameter, T, that takes a class template of the same type parameter, T, as an argument, then typical template usage scenario goes like this:
> >
> >        /* Class template definition */
> >        class Foo(T) {
> >        }
> >
> >        /* Function template definition */
> >        void bar(T)( Foo!(T) arg) {
> >                // ...
> >        }
> >
> >        /* Instantiation usage */
> >        main()
> >        {
> >                auto foo = new Foo!(float)();   /* line A */
> >                bar!(float)( foo);                      /* line B */
> >        }
> >
> >
> > /* Less-noisy instantiation usage */
> > main()
> > {
> >        auto foo = new Foo!(float)();   /* line A */
> >        bar( foo);                                      /* line B */
> > }
> >
> >

> class Foo(T) {}
> void bar(T : Foo!(U), U)(T t) {}
> 
> void main()
> {
> 	auto foo = new Foo!(float)();
> 	bar(foo);
> }
> 
> 
> :)


Wow Jarret!!!  So many words on my part to explain what I wanted and you came up with this just so, so coolly concise solution.  It doesn't exactly look like a textbook solution so me thinks I can forgive myself for not figuring it out. (hey only 3 weeks into D now).

I don't know if it would be pushing my luck or not, but is your concept generalizable to more parameters.  In particular I want to be able to extend this so than bar() can return a generic type.

So now I have this:

class Foo(T)
{}

T2 bar(T : Foo!(U), U)(T t)
{
  T2 x = ...
  return x;
}

void main()
{
 	auto foo = new Foo!(float)();
 	auto chu = bar!(double, float)( foo);
       // type of chu is double
}
 
and by analogy with the first problem I would like to instantiate like so:

void main()
{
 	auto foo = new Foo!(float)();
 	auto chu = bar!(double)( foo);    // be nice if float could be deduced from foo parameter
       // type of chu is double
}


Thanks muchly,

-- Justin





More information about the Digitalmars-d mailing list