Pass type directly to a template function?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 7 02:21:20 PST 2017


On Tuesday, 7 February 2017 at 09:17:04 UTC, Chris Katko wrote:
> Can I pass a type, instead of a variable of a type, to a 
> template function in order to decide the datatype of T in a 
> function?

Yes. That's rather the point.


>     function1(f); //works

That is actually shorthand for this:

function1!float(f);

The compiler is inferring the type of f for you.


>
>     function2!float(); //?
>     function3!float(); //?

Yes, this is how it's done.

>     function3(float);  //?
>     function3(double); //?

No. This won't compile.

>
>
>
> It seems like this would be a useful construct for Factory 
> pattern that assembles any class that you specify as long as 
> the called methods work out. (ala Duck Typing, "if it walks() 
> and quacks() like a duck, it's a duck")

The range infrastructure is based on this concept.





More information about the Digitalmars-d-learn mailing list