overloading functions against function templates

Michal Minich michal.minich at gmail.com
Fri Jul 31 01:55:02 PDT 2009


bearophile wrote:

> import std.stdio: writeln;
> double foo(int x) { return x * 2; }
> double foo(float x) { return x * 3; } double foo(T)(T x) { return x * 4;
> }
> double foo(T : double)(T x) { return x * 5; } void main() {
>     writeln(foo(10));    // prints:
>     writeln(foo(10.5));  // prints:
>     writeln(foo(10.5f)); // prints:
>     writeln(foo(10U));   // prints:
> }
> 
> What's the output?
> I think functions have to be used first, when possible, to reduce
> "template bloat".

I'm not sure by choosing function first, code size will be lower. 
I'm not sure how dmd works, but I think by choosing template foo, code 
will be generated only once for both Point and size classes. 
(correct me if I'm wrong)

Thus I agree the functions should be chosen first, because functions are 
more specific.

class Point { int x, y; }
class Size { int width, height; }


void foo (Point P) { ... }
void foo (Size s) { ... }
void foo (T) (T t) { ... }

void main () { 
  foo (new Point());
  foo (new Point());  
}



More information about the Digitalmars-d mailing list