Pass type directly to a template function?

Chris Katko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 7 01:17:04 PST 2017


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?

void function(T)(T x) //works
      {
     T data;
     //do stuff with T, ignoring x.
     }


void function2(T)() //hypothetical, specify the type... somehow?
     {
     T data;
     }

void function3(T)(T) //hypothetical, specify the datatype in the 
argument list
     {
     T data;
     }


void main()
     {
     float f=0;
     float d=0;
     function1(f); //works
     function1(d); //works

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

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



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")




More information about the Digitalmars-d-learn mailing list