Function template parameter inference from class template argument

Jarrett Billingsley jarrett.billingsley at gmail.com
Wed Sep 23 07:19:40 PDT 2009


On Wed, Sep 23, 2009 at 9:55 AM, Justin Johansson
<procode at adam-dott-com.au> wrote:
> D1.0
>
> 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 */
>        }
>
>
> Now since in the main function the compiler knows that T is float at line A, it occurs to me that code noise could be reduced a bit if the compiler could somehow deduce at line B that the function template parameter, T, is float without it having to be explicitly written.
>
> The instantiation usage would now look like this:
>
> /* Less-noisy instantiation usage */
> main()
> {
>        auto foo = new Foo!(float)();   /* line A */
>        bar( foo);                                      /* line B */
> }
>
>
> The only problem is how then to write the function template definition so that T can be defaulted to the class parameter, T, that accompanies Foo.
>
> One idea I had, which of course doesn't work, is to define the function template's argument with the auto keyword and then somehow figure out T from the argument like so:
>
>        /* Function template definition */
>        void bar(T = typeof( arg))( auto arg) {
>                // ...
>        }
>
>
> Since I'm getting used to finding cool features in D that always lets you do stuff you never dreamed of,
> and since I have a lot of template instantiation code,
> it would be really neat to be able to reduce the noise a bit as outlined above.
>
> Any ideas anybody? (Note D1.0)
>
> Perhaps this is a no brainer and I just goofed up but have given up after a spending way too much time on it thus far.
>
> Thanks all.
>
> Justin Johansson
>
>

class Foo(T) {}
void bar(T : Foo!(U), U)(T t) {}

void main()
{
	auto foo = new Foo!(float)();
	bar(foo);
}


:)



More information about the Digitalmars-d mailing list